Python:定义一个函数来计算sin(x)

2024-06-16 07:21:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我必须定义一个用于计算sin()的函数,程序将使用以下表达式展开序列,直到序列中下一项的绝对值小于1.0e-7

Expressing the Function sin x as a Series

这就是我目前所得到的,但我知道这还远远不够:

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))))

Tags: 函数in程序numberfor定义range序列
3条回答

我会这样做,它使用公式,但不是直接的

  • (-1) ** n是前一个值乘以-1
  • x ** (2n + 1)是前一个值乘以x * x
  • (2n + 1)!是前一个值乘以2n * (2n + 1)

这意味着您的循环不进行幂或阶乘计算,这会更有效一些。这是Python的版本:

def approx_sin(x, eps=1e-7):
    term = x
    two_n = 0
    total = 0

    while abs(term) >= eps:
        total += term
        two_n += 2
        term *= -x * x / (two_n * (two_n + 1))

    return total

假设这是一个无穷级数,您可以创建一个生成器,通过每次递增n,使给定的x提供下一个求值

from math import factorial, pow

def sin_gen(x):
    n = 0
    while True:
        result = (pow(-1, n) * pow(x, (2 * n + 1))) / factorial(2 * n + 1)
        yield result
        n += 1

现在您只需要对每个评估求和,直到总数达到您想要的值

g = sin_gen(x)
total = 0

for val in g: 
    if abs(val) < 1.0e-7: 
        break 
    total += val

print(total)

小心-1 ** n,它没有像您预期的那样被解析**比一元数-(具有更高的优先级)绑定更紧密,因此此表达式的解析方式类似于-(1 ** n)。类似于Blueteiths解决方案,我会做如下操作

from math import factorial, pow
from itertools import takewhile, count

large = lambda y: abs(y) > 1e-7

def sin_gen(x):
    for n in count():
        yield (pow(-1, n) * pow(x, (2 * n + 1))) / factorial(2 * n + 1)


def sin(x):
    return sum(takewhile(large, sin_gen(x)))

print(sin(5))  # -0.9589242932128198

相关问题 更多 >