Created
November 9, 2012 18:30
-
-
Save anonymous/4047379 to your computer and use it in GitHub Desktop.
Calculate e
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <math.h> | |
#include <gmp.h> // Bignum support | |
int main(void) { | |
long long iteration=0; | |
mpq_t current_term; /* Contains 1/n! */ | |
mpq_t sum; /* Contains sum over all 1/n! */ | |
mpf_t result; /* Contains the denominator first, then e */ | |
mpf_t divisor; | |
mpq_init(current_term); | |
mpq_init(sum); | |
/* | |
* We calculate E using Taylor series expansion. We know from Wikipedia that | |
* e can be calculated using the following formula. | |
* | |
* oo | |
* ____ | |
* \ 1 | |
* e = ) ----- | |
* /___ n! | |
* i=0 | |
* | |
* Because calculating the fraction every time takes a long time, we just | |
* calculate the denominator and the numerator and add them. When we are | |
* done summing up all the terms, we finally do the division. | |
*/ | |
/* Make sure numerator is always 1 */ | |
mpz_set_ui(mpq_numref(current_term), 1); | |
printf("Starting main summing..."); | |
for(;iteration<3500;iteration++) { | |
mpz_fac_ui(mpq_denref(current_term), iteration); /* set the denominator of current_term | |
to the factorial of n */ | |
// Add current term to result. | |
mpq_add(sum, sum, current_term); | |
} | |
printf("done\nStarting division..."); | |
/* Finally divide integers */ | |
mpf_init2(result, 100000); | |
mpf_init2(divisor, 100000); | |
mpf_set_z(result, mpq_numref(sum)); | |
mpf_set_z(divisor, mpq_denref(sum)); | |
mpf_div(result, result, divisor); | |
printf("done\n"); | |
printf("Result: "); | |
mpf_out_str(stdout, 10, 1000, result); | |
printf("\n"); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CC=gcc | |
euler: euler.o | |
$(CC) -lgmp -o euler euler.o | |
euler.o: euler.c | |
$(CC) -O3 -c euler.c -o euler.o | |
.PHONY: clean | |
clean: | |
rm -f euler.o euler |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment