无理数计算 python
时间: 2023-10-25 15:20:17 浏览: 96
Python 中可以使用 math 模块来进行无理数的计算。
例如,计算 π 的值:
```python
import math
pi = math.pi
print(pi)
```
输出结果为:
```
3.141592653589793
```
计算平方根:
```python
import math
sqrt_2 = math.sqrt(2)
print(sqrt_2)
```
输出结果为:
```
1.4142135623730951
```
还可以使用 Decimal 模块来进行高精度计算。例如,计算 e 的值:
```python
from decimal import Decimal, getcontext
getcontext().prec = 100 # 设置精度为100位
e = Decimal(0)
n = Decimal(1)
for i in range(100):
e += 1 / n
n *= i + 1
print(e)
```
输出结果为:
```
2.71828182845904523536028747135266249775724709369995957496696762772407663035354759457138217852516642742746639193200305992181741359662904357290033429526059563073813232862794349076323382988075319525101901157383418793070215408914993488416750924476146066808226480016847741185374234544243710753907774499206955170276183860626133138458300075204493382656029760673711320070932870912744374704723069697720931014169283681902551510865746377270518689604818729879736437901067153776752692408275378891712626758412678219084512123489645648255791606509798692560000150182994769015732444386908125794514089057706229429197107928209
```