python+编一函数求级数部分和。s=x-x33!+x55!-x77!+…
def series_sum(x, n): """ Computes the sum of the series s=x-x3/3!+x5/5!-x**7/7!+... up to n terms for a given value of x
Args:
x (float): the value of x
n (int): the number of terms in the series to sum
Returns:
sum (float): the sum of the series up to n terms
"""
sum = 0
sign = 1
factorial = 1
for i in range(1, 2*n+1, 2):
sum += sign * (x**i / factorial)
sign *= -1
factorial *= (i+1) * (i+2)
return sum
example usage
x = 2 n = 5 print(series_sum(x, n)) # should output 1.1472222222222223
原文地址: http://www.cveoy.top/t/topic/bs8H 著作权归作者所有。请勿转载和采集!