我试图写一个程序,它以度为单位,根据用户选择的一些给定项来近似sin和cos值。万一你不知道 how寻找罪与果。所以,我现在的代码是:
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。我假设这是我在第一个循环中把值相加的方式,但我可能错了。感谢任何帮助!在
正如Russell Borogove's comments中指出的,这里有几个问题。在
第一个问题是你使用的公式
(见wikipedia)期望x是弧度而不是度数。绕一个圆一圈是360度或2*pi,因此可以通过乘以pi/180将度数转换为弧度,如下python代码中所示,这样可以错误地获得90度的sin。在
问题2是代码的其余部分。正如在评论中指出的,有一些bug,找到它们的最好方法是使用一些战略性的
print
语句。然而,你可以用更少的代码行来编写你的程序,而简单的程序往往会有更少的错误,如果它们确实有问题,则更容易调试。在因为这是一个作业,我不会为您做,但是一个相关的例子是sinh(x)的系列。在
(再次来自维基百科)
您可以使用Pythonlist comprehension在“one shot”中生成术语。可以对列表进行
^{pr2}$print
ed和sum
med来获得结果,如下面的程序所示这个程序的输出是
我直接从求和的数学公式中生成了Python列表理解代码,它在左侧以“Sigma”表示法方便地给出。你也可以用同样的方式产生罪恶和罪恶。你需要的一个缺少的成分是系列中每一点的符号。数学公式告诉你你需要(-1)n。Python的等价物是
(-1)**n
,它可以被安排到列表理解代码的适当位置。在下面是一个改进版本:
请注意,由于麦克劳林级数以x=0为中心,接近0的θ值收敛得更快:}为-0.444365928238(与-1.0的正确值相差约157000倍)。在
calc_sin(radians(-90), 5)
为-1.00000354258,而{首先,一些注意事项。最好在上一次打印结束时打印
\n
,或者在下一次打印的开始处打印print()
。 使用调试工具、使用logging
模块或仅使用print
并通过将预期值与返回值进行比较来查找错误,这是很有用的。在下面是一个对我有用的代码:
我改变了什么?(我希望我不会忘记什么)
sign
变量错误。恰恰相反。所以我改变了条件中的符号。在num
除以denom
时,我添加了从int到float的转换。在x
是以弧度表示的。所以我增加了从度到弧度的转换。x = x / 180.0 * math.pi;
calcCosFact
中的索引错误。它总是高出2。(即4代替2,8代替6…)我得到了这个结果: 输入角度(以度为单位):180输入要使用的术语数:5 成本:-0.97602221624, 窦:0.00692527070751在
现在应该是对的。当你需要快速计算数学时,我也可以推荐WolphramAlpha。在
相关问题 更多 >
编程相关推荐