Skip to content

Instantly share code, notes, and snippets.

@jnbek
Created April 4, 2017 18:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jnbek/6cff74c91ad3c8bb8b346a56b6fb525a to your computer and use it in GitHub Desktop.
Save jnbek/6cff74c91ad3c8bb8b346a56b6fb525a to your computer and use it in GitHub Desktop.
bc script
#!/usr/bin/bc -l
scale = 20
/* Uses the fact that e^x = (e^(x/2))^2
When x is small enough, we use the series:
e^x = 1 + x + x^2/2! + x^3/3! + ...
*/
define e(x) {
auto a, d, e, f, i, m, v, z
/* Check the sign of x. */
if (x<0) {
m = 1
x = -x
}
/* Precondition x. */
z = scale;
scale = 4 + z + .44*x;
while (x > 1) {
f += 1;
x /= 2;
}
/* Initialize the variables. */
v = 1+x
a = x
d = 1
for (i=2; 1; i++) {
e = (a *= x) / (d *= i)
if (e == 0) {
if (f>0) while (f--) v = v*v;
scale = z
if (m) return (1/v);
return (v/1);
}
v += e
}
}
e(2)
e(10)
quit
./bc
bc 1.06.95
Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'.
7.38905609893065022723
22026.46579480671651695790
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment