Skip to content

Instantly share code, notes, and snippets.

@gabrielfern
Created October 29, 2018 23:58
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 gabrielfern/3de42c274878f4c5d3cafe3e606183b3 to your computer and use it in GitHub Desktop.
Save gabrielfern/3de42c274878f4c5d3cafe3e606183b3 to your computer and use it in GitHub Desktop.
Leibniz to find π
#include <stdio.h>
#include <stdlib.h>
double calc(unsigned long n) {
unsigned long i = 0;
double sum = 0;
while (i < n) {
sum += (i%2 == 0 ? 1.0 : -1.0) / (2*i+1);
i++;
}
return sum*4;
}
int main(int c, char **arr) {
printf("%.20f\n", calc(atol(arr[1])));
}
#!/usr/bin/env python3
from sys import argv
def calc(n):
i = 0
sum = 0
while i < n:
sum += (1 if i%2 == 0 else -1) / (2*i+1)
i += 1
return sum*4
if __name__ == '__main__':
print('%.20f' %calc(int(argv[1])))
#!/usr/bin/env python3
from sys import argv
import ctypes
pic = ctypes.cdll.LoadLibrary('./libpi.so')
pic.calc.restype = ctypes.c_double
print('%.20f' %pic.calc(ctypes.c_ulong(int(argv[1]))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment