Python 发出程序以近似正弦和余弦值
我正试图编写一个程序,它以度为单位,根据用户选择的一些给定术语来近似正弦和余弦值。万一你不知道 寻找罪恶和罪恶。话虽如此,以下是我当前的代码:Python 发出程序以近似正弦和余弦值,python,math,Python,Math,我正试图编写一个程序,它以度为单位,根据用户选择的一些给定术语来近似正弦和余弦值。万一你不知道 寻找罪恶和罪恶。话虽如此,以下是我当前的代码: 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
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.500000004334333和sin=0.866025445100。我假设这是我在第一个循环中将值相加的方式,但我可能错了。感谢您的帮助 如中所述,这里有几个问题 问题1是您使用的公式 (请参见)x的单位应为弧度,而不是度。绕一个圆一圈是360度或2*pi,因此可以通过乘以pi/180将角度转换为弧度,如下python代码所示,从而正确地获得90度的sin
>>> math.sin(90)
0.8939966636005579
>>> math.sin(90*math.pi/180)
1.0
第2期是代码的其余部分。正如评论中指出的,存在一些bug,找到它们的最佳方法是使用一些战略性的打印语句。然而,您可以用更少的代码行编写程序,而更简单的程序往往有更少的bug,如果它们确实有问题,则更容易调试
因为这是一个作业,我不会为你做,但是一个相关的例子是sinh(x)系列
(再次摘自维基百科)
您可以使用Python以“一次性”的形式生成术语。列表可以是print
ed和sum
med以获得结果,如下程序所示
x = 90 * math.pi / 180 # 90 degrees
n = 5
terms = [x**(2*i+1)/math.factorial(2*i+1) for i in range(n)]
print terms
sinh = sum(terms)
print sinh, math.sinh(x)
这个程序的输出是
[1.5707963267948966, 0.6459640975062462, 0.07969262624616703, 0.004681754135318687, 0.00016044118478735975]
2.30129524587 2.30129890231
我直接从求和的数学公式中生成了Python列表理解代码,该公式在左侧以“Sigma”符号方便地给出。你可以用类似的方式制造罪恶和罪恶。你需要的一个缺少的元素是系列中每个点的符号。数学公式告诉你你需要(-1)n。Python的等价物是(-1)**n
,可以将其插入列表理解代码中的适当位置。首先,请注意几点。最好在上一次打印结束或下一次打印开始时打印\n
,然后清空print()
。
使用调试工具、使用日志记录
模块或仅使用打印
并通过比较预期值和返回值来查找错误是很有用的
下面是一个适用于我的代码:
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()
x = x / 180.0 * math.pi; # added
for i in range(1, terms+1):
sinx = sinx + getSin(i, x)
cosx = cosx + getCos(i, x)
print("Cos:{0}, Sinus:{1}".format(cosx,sinx)); # changed
def getSin(i, x):
if i == 1:
return x
else:
num, denom = calcSinFact(i, x)
sin = float(num)/denom # changed
return sin
def getCos(i, x):
if i == 1:
return 1
else:
num, denom = calcCosFact(i, x)
cos = float(num)/denom # changed
return cos
def calcSinFact(i, x):
if i % 2 == 1:
sign = +1 # changed
if i % 2 == 0:
sign = -1 # changed
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 # changed
if i % 2 == 0:
sign = -1 # changed
denom = math.factorial(i*2-2) # changed
num = sign * (x**(i*2-2)) # changed
return num, denom
我改变了什么?(我希望我不会忘记任何事情)
您的符号
变量错误。恰恰相反。所以我改变了条件中的标志
这可能不是必需的,但当您将num
除以denom
时,我添加了从int到float的转换
根据,输入x
以弧度为单位。所以我增加了从度到弧度的转换<代码>x=x/180.0*math.pi代码>
您在calcCosFact
中的索引错误。它总是高出2。(即4而不是2,8而不是6…)
我得到了这个结果:
输入角度(以度为单位):180输入要使用的术语数:5
Cos:-0.976022212624,窦:0.006925270751
现在应该是正确的。当你需要快速计算时,我也可以推荐你。这里有一个改进版本:
from math import radians
import sys
# version compatibility shim
if sys.hexversion < 0x3000000:
# Python 2.x
inp = raw_input
rng = xrange
else:
# Python 3.x
inp = input
rng = range
def type_getter(type):
def fn(prompt):
while True:
try:
return type(inp(prompt))
except ValueError:
pass
return fn
get_float = type_getter(float)
get_int = type_getter(int)
def calc_sin(theta, terms):
# term 0
num = theta
denom = 1
approx = num / denom
# following terms
for n in rng(1, terms):
num *= -theta * theta
denom *= (2*n) * (2*n + 1)
# running sum
approx += num / denom
return approx
def calc_cos(theta, terms):
# term 0
num = 1.
denom = 1
approx = num / denom
# following terms
for n in rng(1, terms):
num *= -theta * theta
denom *= (2*n - 1) * (2*n)
# running sum
approx += num / denom
return approx
def main():
print(
"\nProgram to approximate sin and cos."
"\nYou will be asked to enter an angle and"
"\na number of terms."
)
theta = get_float("Enter an angle (in degrees): ")
terms = get_int ("Number of terms to use: ")
print("sin({}) = {}".format(theta, calc_sin(radians(theta), terms)))
print("cos({}) = {}".format(theta, calc_cos(radians(theta), terms)))
if __name__=="__main__":
main()
从数学导入弧度
导入系统
#版本兼容性垫片
如果sys.hexversion<0x3000000:
#Python2.x
inp=原始输入
rng=xrange
其他:
#Python3.x
inp=输入
rng=范围
def类型吸气剂(类型):
def fn(提示):
尽管如此:
尝试:
返回类型(inp(提示))
除值错误外:
通过
返回fn
获取\u浮点=类型\u getter(浮点)
get\u int=类型\u getter(int)
def calc_sin(θ,术语):
#第0项
num=θ
denom=1
近似值=num/denom
#下列条款
对于rng中的n(1,术语):
num*=-θ*θ
denom*=(2*n)*(2*n+1)
#流水
近似值+=num/denom
返回大约
def calc_uCOS(θ,术语):
#第0项
num=1。
denom=1
近似值=num/denom
#下列条款
对于rng中的n(1,术语):
num*=-θ*θ
denom*=(2*n-1)*(2*n)
#流水
近似值+=num/denom
返回大约
def main():
印刷品(
“\n近似正弦波和余弦波的程序。”
“\n将要求您输入角度和”
“\n术语的数目。”
)
θ=获取浮点(“输入角度(以度为单位):”)
terms=get_int(“要使用的术语数量:”)
打印(“sin({})={}”。格式(θ,计算sin(弧度(θ),术语)))
打印(“cos({})={}”。格式(θ,计算cos(弧度(θ),术语)))
如果名称=“\uuuuu main\uuuuuuuu”:
main()
请注意,由于麦克劳林级数以x=0为中心,θ值接近0时收敛速度会快得多:calcêsin(弧度(-90),5)
为-1.00000354258,但calcêsin(弧度(270),5)
为-0.444365928238(距离正确的-1.0大约157000倍)通过使用并结合阶乘和整数幂的递归定义,可以完全避免所有幂和阶乘计算。进一步的优化是通过同时计算cos和sin值来实现的,因此功率只计算一次
PI = 3.1415926535897932384;
RadInDeg=PI/180;
def getCosSin(x, n):
mxx = -x*x;
term = 1;
k = 2;
cossum = 1;
sinsum = 1;
for i in range(n):
term *= mxx
term /= k; k+=1
cossum += term
term /= k; k+=1
sinsum += term
return cossum, x*sinsum
def main():
print "\nProgram to approximate sin and cos."
print "You will be asked to enter an angle and \na number of terms."
x = int(input("Enter an angle (in degrees): "))
terms = int(input("Enter the number of terms to use: "))
print
x = x*RadInDeg;
cosx, sinx = getCosSin(x,terms)
print cosx, sinx
if __name__=="__main__":
main()
如果这些选项被禁用,那么您期望的值是什么?胡乱猜测:您正在以度为单位进行输入,并将其用于期望弧度的算法中。试着将初始输入乘以pi/180。除此之外,你的术语是错误的。尝试在getSin()
和getCos()
中添加print语句,以打印术语索引、分子和分母,找出错误所在。