编写函数fun,功能是计算如下多项式:s=1+x+x**2/2!+x**3/3!+•••+x**n/n!
时间: 2023-11-03 11:01:44 浏览: 105
Sure! 下面是函数fun的代码,可以计算给定n和x下的多项式值:
```python
import math
def fun(n, x):
s = 0
for i in range(1, n+1):
s += (x ** i) / math.factorial(i)
return s
```
希望能够帮到您!如果您还有其他问题,欢迎随时提出。
相关问题
编写函数fun,计算下列多项式:s=1+x+x**2/2!+x**3/3!+•••+x**n/n!
Sure, I can help you with that! Here is the function:
```python
def fun(x, n):
s = 1
fact = 1
for i in range(1, n+1):
fact *= i
s += (x ** i) / fact
return s
```
Simply pass in the value of `x` and the number of terms `n` you want to use in the approximation. The function will return the value of the sum of the series.
Hope this helps!
c语言编写函数fun,其功能是:计算并输出下列多项式值:Sn=1+1/1!+1/2!+1/3!+1/4!+......+1/n!
以下是C语言编写的函数fun,其功能是计算并输出多项式值Sn=1+1/1!+1/2!+1/3!+1/4!+......+1/n!:
```c
#include <stdio.h>
double fun(int n) {
double t, sn = 1.0;
int i, j;
for (i = 1; i < n; i++) {
t = 1.0;
for (j = 1; j <= i; j++) {
t = t * j;
}
sn += 1.0 / t;
}
return sn;
}
int main() {
double sum = fun(4);
printf("sum is %f\n", sum);
return 0;
}
```
其中,fun函数的参数n表示要计算多项式的前n项的和,函数返回值为多项式的和。在函数中,使用了两个循环,分别计算阶乘和多项式的和。在计算阶乘时,使用了变量t来保存每一项的阶乘值,然后将其加入到多项式的和中。