【发布时间】:2014-03-31 22:40:58
【问题描述】:
我正在尝试编写一个程序,它以度为单位,并根据用户选择的多个给定项来近似 sin 和 cos 值。如果你不知道 how寻找罪和cos。所以,话虽如此,这是我当前的代码:
import math
def main():
print()
print("Program to approximate sin and cos.")
print("You will be asked to enter an angle and \na number of terms.")
print("Written by ME")
print()
sinx = 0
cosx = 0
x = int(input("Enter an angle (in degrees): "))
terms = int(input("Enter the number of terms to use: "))
print()
for i in range(1, terms+1):
sinx = sinx + getSin(i, x)
cosx = cosx + getCos(i, x)
print(cosx, sinx)
def getSin(i, x):
if i == 1:
return x
else:
num, denom = calcSinFact(i, x)
sin = num/denom
return sin
def getCos(i, x):
if i == 1:
return 1
else:
num, denom = calcCosFact(i, x)
cos = num/denom
return cos
def calcSinFact(i, x):
if i % 2 == 1:
sign = -1
if i % 2 == 0:
sign = +1
denom = math.factorial(i*2-1)
num = sign * (x**(i*2-1))
return num, denom
def calcCosFact(i, x):
if i % 2 == 1:
sign = -1
if i % 2 == 0:
sign = +1
denom = math.factorial(i*2)
num = sign * (x**(i*2))
return num, denom
它可以运行,但如果我使用上图所示的示例,我会得到 cos = -162527117141.85715 和 sin = -881660636823.117。很明显有些事情不对劲。在上图中,答案应该是 cos = 0.50000000433433 和 sin = 0.866025445100。我假设这是我在第一个循环中将值相加的方式,但我可能是错的。任何帮助表示赞赏!
【问题讨论】:
-
如果关闭,您期望的值是多少?
-
大胆猜测:您以度为单位输入,并在需要弧度的算法中使用它。尝试将初始输入乘以 pi/180。
-
而且你的条款是错误的。尝试在
getSin()和getCos()中添加打印语句以打印术语索引、分子和分母,以找出哪里出错了。