|
本帖最后由 hbghlyj 于 2022-8-27 18:36 编辑
A tiny program to compute e
This is a tiny C program from Xavier Gourdon to compute 9000 decimal digits of $e$ on your computer. A program of the same kind exists for $π$ and for some other constants defined by mean of hypergeometric series.
- #include <stdio.h>
- int main(){int N=9009,n=N,a[9009],x;
- while(--n)a[n]=1+1/n;
- for(;N>9;printf("%d",x))
- for(n=N--;--n;a[n]=x%n,x=10*a[n-1]+x/n);}
复制代码
第3行while(--n)a[n]=1+1/n;的作用是把数组a设为{0,2,1,1,1,⋯,1}
Horner's way
$$\mathrm{e}=\left(\left(\left(\left((\ldots+1) \frac{1}{6}+1\right) \frac{1}{5}+1\right) \frac{1}{4}+1\right) \frac{1}{3}+1\right) \frac{1}{2}+2$$so that, if we evaluate it by starting with the last terms of series (3), only divisions by small integers will be required (the addition of 1 being of a quasi-null cost when working with a large accuracy) and fewer storage memory is needed. The algorithm, which converges to $e-1$, now looks like:
$\left\{\array{\vphantom{f}\\\vphantom{f}}\right.$ | u=(1+u)/n --n | (10) |
with initial values $u=1, n=K$ and (10) should be repeated until $n=1$. |
|