在阅读本文之前:这可能不是正确的答案,因为它效率极低,但如果您需要额外的精度,这可能是最好的解决方案。
您可以使用Decimal
类,您可以在其中使用所需的任何精度进行计算(它使用字符串对象而不是整数进行计算)。
>>> from decimal import *
>>> getcontext().prec = 30
>>> Decimal(1) / Decimal(7)
Decimal('0.142857142857142857142857142857')
但问题是您必须实现自己的三角函数。幸运的是 python 网站提供了示例:
https://docs.python.org/3/library/decimal.html#recipes https://docs.python.org/3/library/decimal.html#recipes
def cos(x):
"""Return the cosine of x as measured in radians.
The Taylor series approximation works best for a small value of x.
For larger values, first compute x = x % (2 * pi).
>>> print(cos(Decimal('0.5')))
0.8775825618903727161162815826
>>> print(cos(0.5))
0.87758256189
>>> print(cos(0.5+0j))
(0.87758256189+0j)
"""
getcontext().prec += 2
i, lasts, s, fact, num, sign = 0, 0, 1, 1, 1, 1
while s != lasts:
lasts = s
i += 2
fact *= i * (i-1)
num *= x * x
sign *= -1
s += num / fact * sign
getcontext().prec -= 2
return +s
请注意,这会影响程序的执行时间,因为使用字符串计算显然比使用浮点数慢得多。