我必须定义一个用于计算sin()
的函数,程序将使用以下表达式展开序列,直到序列中下一项的绝对值小于1.0e-7
:
这就是我目前所得到的,但我知道这还远远不够:
number = input("\n\tEnter X: ")
x_flt = float(number)
x_int = int(x_flt)
x_approx = 0
for i in range(1, x_int+1):
factor = x_flt * i
def approximate_sin(x):
'''Insert docstring here.'''
for a in range():
x_approx = (-1 ** a * x ** (2 * a + 1)) / factor
return x_approx
print("\n\tApproximation: {:.10f}".format(float(approximate_sin(x_flt))))
我会这样做,它使用公式,但不是直接的
(-1) ** n
是前一个值乘以-1
李>x ** (2n + 1)
是前一个值乘以x * x
李>(2n + 1)!
是前一个值乘以2n * (2n + 1)
李>这意味着您的循环不进行幂或阶乘计算,这会更有效一些。这是Python的版本:
假设这是一个无穷级数,您可以创建一个生成器,通过每次递增n,使给定的x提供下一个求值
现在您只需要对每个评估求和,直到总数达到您想要的值
小心
-1 ** n
,它没有像您预期的那样被解析**
比一元数-
(具有更高的优先级)绑定更紧密,因此此表达式的解析方式类似于-(1 ** n)
。类似于Blueteiths解决方案,我会做如下操作相关问题 更多 >
编程相关推荐