有没有办法获得一个角度的精确切线/余弦/正弦(弧度)?
math.tan()/ math.sin()/ math.cos()没有给出确切一些角度:
>>> from math import *
>>> from decimal import Decimal
>>> sin(pi) # should be 0
1.2246467991473532e-16
>>> sin(2*pi) # should be 0
-2.4492935982947064e-16
>>> cos(pi/2) # should be 0
6.123233995736766e-17
>>> cos(3*pi/2) # 0
-1.8369701987210297e-16
>>> tan(pi/2) # invalid; tan(pi/2) is undefined
1.633123935319537e+16
>>> tan(3*pi/2) # also undefined
5443746451065123.0
>>> tan(2*pi) # 0
-2.4492935982947064e-16
>>> tan(pi) # 0
-1.2246467991473532e-16
Run Code Online (Sandbox Code Playgroud)
我尝试使用Decimal(),但这也无济于事:
>>> tan(Decimal(pi)*2)
-2.4492935982947064e-16
Run Code Online (Sandbox Code Playgroud)
numpy.sin(x) 和其他三角函数也有相同的问题.
或者,我总是可以创建一个带有值字典的新函数,例如:
def new_sin(x):
sin_values = {math.pi: 0, 2*math.pi: 0}
return sin_values[x] if x in sin_values.keys() else math.sin(x)
Run Code Online (Sandbox Code Playgroud)
然而,这似乎是一种廉价的解决方法.还有其他方法吗?谢谢!
在计算机中存储pi的精确数值是不可能的.math.pi是最接近pi的近似值,可以存储在Python float中.math.sin(math.pi)返回近似输入的正确结果.
为避免这种情况,您需要使用支持符号算术的库.例如,与sympy:
>>> from sympy import *
>>> sin(pi)
0
>>> pi
pi
>>>
Run Code Online (Sandbox Code Playgroud)
sympy将对代表pi的对象进行操作,并且可以给出准确的结果.
| 归档时间: |
|
| 查看次数: |
4111 次 |
| 最近记录: |