Python 3.x 如何编写cos(1)
我需要找到一种使用while循环在python中编写cos(1)的方法。但是我不能使用任何数学函数。有人能帮我吗 例如,我还必须编写exp(1)的值,我可以通过编写:Python 3.x 如何编写cos(1),python-3.x,Python 3.x,我需要找到一种使用while循环在python中编写cos(1)的方法。但是我不能使用任何数学函数。有人能帮我吗 例如,我还必须编写exp(1)的值,我可以通过编写: count = 1 term = 1 expTotal = 0 xx = 1 while abs(term) > 1e-20: print("%1d %22.17e" % (count, term)) expTotal = expTotal + term term=term * xx/
count = 1
term = 1
expTotal = 0
xx = 1
while abs(term) > 1e-20:
print("%1d %22.17e" % (count, term))
expTotal = expTotal + term
term=term * xx/(count)
count+=1
我完全不知道如何用cos和sin值来做这件事 您可以使用此函数的泰勒展开式来计算cos(1): 您可以在上找到更多详细信息,请参阅下面的实现:
import math
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
def cos(order):
a = 0
for i in range(0, order):
a += ((-1)**i)/(factorial(2*i)*1.0)
return a
print cos(10)
print math.cos(1)
这将作为输出提供:
0.540302305868
0.540302305868
Actual cos: 0.540302305868
Cordic cos: 0.540302305869
编辑:显然,余弦是在硬件中使用算法实现的,该算法使用查找表来计算atan
。下面是基于此Google组的CORDIS算法的Python实现:
只需将表达式更改为将术语计算为:
term = term * (-1 * x * x)/( (2*count) * ((2*count)-1) )
将计数乘以2可以更改为将计数增加2,因此,下面是您的副本:
import math
def cos(x):
cosTotal = 1
count = 2
term = 1
x=float(x)
while abs(term) > 1e-20:
term *= (-x * x)/( count * (count-1) )
cosTotal += term
count += 2
print("%1d %22.17e" % (count, term))
return cosTotal
print( cos(1) )
print( math.cos(1) )
import math
def cos(x):
cosTotal = 1
count = 2
term = 1
x=float(x)
while abs(term) > 1e-20:
term *= (-x * x)/( count * (count-1) )
cosTotal += term
count += 2
print("%1d %22.17e" % (count, term))
return cosTotal
print( cos(1) )
print( math.cos(1) )