Writing a Python function to calculate Pi - python

newbie here:
Just learning Python and this one has me pooped. It's coming up with a function for manually computing Pi, the Madhava way. - Also known as exercise #16 from here: http://interactivepython.org/courselib/static/thinkcspy/Functions/thinkcspyExercises.html
Can somebody take a look at my discombobulated and overly complex code and tell me if I'm missing something? Much thanks. (look at the equation on the wiki page first, otherwise my code will make no sense - well, it still may not.)
import math
def denom_exp(iters):
for i in range(0, iters):
exp = 3^iters
return exp
def base_denom(iters):
for i in range(0, iters):
denom = 1 + 2*iters
return denom
def myPi(iters):
sign = 1
pi = 0
for i in range(0, iters):
pi = pi + sign*(1/((base_denom(iters))*denom_exp(iters)))
sign = -1 * sign
pi = (math.sqrt(12))*pi
return pi
thisisit = myPi(10000)
print(thisisit)

Try this code, manually computing Pi, the Madhava way.
import math
def myPi(iters):
sign = 1
x = 1
y = 0
series = 0
for i in range (iters):
series = series + (sign/(x * 3**y))
x = x + 2
y = y + 1
sign = sign * -1
myPi = math.sqrt(12) * series
return myPi
print(myPi(1000))

Related

Converting Mathematica Fourier series code to Python

I have some simple Mathematica code that I'm struggling to convert to Python and could use some help:
a = ((-1)^(n))*4/(Pi*(2 n + 1));
f = a*Cos[(2 n + 1)*t];
sum = Sum[f, {n, 0, 10}];
Plot[sum, {t, -2 \[Pi], 2 \[Pi]}]
The plot looks like this:
For context, I have a function f(t):
I need to plot the sum of the first 10 terms. In Mathematica this was pretty straighforward, but for some reason I just can't seem to figure out how to make it work in Python. I've tried defining a function a(n), but when I try to set f(t) equal to the sum using my list of odd numbers, it doesn't work because t is not defined, but t is a variable. Any help would be much appreciated.
Below is a sample of one of the many different things I've tried. I know that it's not quite right in terms of getting the parity of the terms to alternate, but more important I just want to figure out how to get 'f' to be the sum of the first 10 terms of the summation:
n = list(range(1,20,2))
def a(n):
return ((-1)**(n))*4/(np.pi*n)
f = 0
for i in n:
f += a(i)*np.cos(i*t)
modifying your code, look the part which are different, mostly the mistake was in the part which you are not calculating based on n 0-10 :
n = np.arange(0,10)
t = np.linspace(-2 * np.pi, 2 *np.pi, 10000)
def a(n):
return ((-1)**(n))*4/(np.pi*(2*n+1))
f = 0
for i in n:
f += a(i)*np.cos((2*i +1) * t)
however you could write you could in matrix form, and avoid looping, using the vector and broadcasting:
n = np.arange(10)[:,None]
t = np.linspace(-2 * np.pi, 2 *np.pi, 10000)[:,None]
a = ((-1) ** n) * 4 / (np.pi*(2*n + 1))
f = (a * np.cos((2 * n + 1) * t.T )).sum(axis=0)

Trigonometric Functions: How do I write Sine and Cosine function's code without using `math` module?

I have been writing code for a module I am making for my Discord Bot. I have been trying not to use any module as it is not helping in in importing stuff. So I thought I should write the code myself for both of them.
The problem here is that I don't really know how do we make them. I couldn't find them anywhere on the net as everywhere I only saw the use of math module which I don't want to use.
I don't know how do I work with them, so I want some help.
Thank You! :)
Using Taylor expansion you get an approximation up to the desired precision.
http://hyperphysics.phy-astr.gsu.edu/hbase/tayser.html
def pow(base, exponent):
return base ** exponent
def faktorial(n):
value = float(1)
for i in range(1, n+1):
value = value * i
return value
def cos(x):
x = x * 3.14/180
value = 1
sign = -1
n = 200 # precision
i = 2
while i < n:
value = value + (pow(x, i)/faktorial(i) * sign)
i = i + 2
sign = sign * -1
return value
def sin(x):
x = x * 3.14/180
value = x
sign = -1
n = 200 # precision
i = 3
while i < n:
value = value + (pow(x, i)/faktorial(i) * sign)
i = i + 2
sign = sign * -1
return value
pi = 3.1415926535897932384626433832795028841971 # Value of constant pi
def f(n): # Factorial Function
if n == 1 or n == 0:
return 1
else:
return n * f(n - 1)
def deg(x):
rad = x * pi/180
return rad
def sin(x): # Taylor Expansion of sinx
k = 0
sinx = 0
while x >= pi:
x -= pi
if pi > x > pi / 2:
x = pi - x
while k < 15:
sinx += (-1)**k * x**(2*k + 1) / f(2*k + 1)
k += 1
return sinx
def cos(x):
cosx = sin(pi / 2 - x)
return cosx
I improved the code now. Now it gives you accurate results of up to 14 decimal places. Also instead of writing full Taylor expression formula, I used a while loop to do that. While loop here acts as a summation function of maths. I also shorten the code inside cos(x). Instead of writing Taylor's expression here, I used a conversion formula of sinx to cosx. Which reduces the calculation process. I made a little change in the code. Now you can calculate sinx of huge number too with the same accuracy.

Numerical method in python- can't spot the problem?

I am writing this numerical method formula of trapezium rule for double integrals.
Note that hx = (b-a)/nx, hy = (d-c)/ny to get the interval widths and xj = a+hxj and yi = c+hyi
A few problems in your code:
First yes your indentation here is off (but I assume it's from not copying it across well since this would lead to an error rather than a wrong value). In the future make sure the indentation in your question corresponds to what you have at on your own computer before posting...
Then a term should be added within a for if and only if it's in the corresponding sum... Here you put everything within the double for loop which corresponds to having all the terms in the double sum.
Finally range(1,n) already stops at n-1 only so you want to remove those -1 in the ranges.
In the end:
def double_integral(f,a,b,c,d,nx,ny):
hx = (b-a)/nx
hy = (d-c)/ny
first_term = (f(a,c)+f(a,d)+f(b,c)+f(b,d))
i_sum = 0
for i in range(1,ny):
i_sum += f(a,c+i*hy)+f(b, c+i*hy)
j_sum = 0
for j in range(1,nx):
j_sum += f(a+j*hx,c)+f(a+j*hx,d)
ij_sum = 0
for i in range(1,ny):
for j in range(1,nx):
ij_sum += f(a+j*hx,c+i*hy)
integral = (first_term/4 + i_sum/2 + j_sum/2 + ij_sum) * hx * hy
return integral
def t(x,y):
return x*(y**(2))
print(double_integral(t,0,2,0,1,10,10))
0.6700000000000003
You'll get closer to 2/3 by choosing numbers of steps larger than 10...
And you can be more pythonic by using sum comprehension:
def double_integral(f,a,b,c,d,nx,ny):
hx = (b-a)/nx
hy = (d-c)/ny
first_term = (f(a,c)+f(a,d)+f(b,c)+f(b,d))
i_sum = sum(f(a,c+i*hy)+f(b, c+i*hy) for i in range (1,ny))
j_sum = sum(f(a+j*hx,c)+f(a+j*hx,d) for j in range(1,nx))
ij_sum = sum(f(a+j*hx,c+i*hy) for i in range (1,ny) for j in range(1,nx))
integral = (first_term/4 + i_sum/2 + j_sum/2 + ij_sum) * hx * hy
return integral

How to find the sum of this series using loops

x - x^2/fact(2) + x^3/fact(3) ... -x^6/fact(6)
I tried various ways, even used nested 'for' loops, but I can't seem to figure out the code, any help?
you could try this; order defines how many terms should be taken into account:
def taylor(x, order=3):
x_n = x
fact = 1
sign = 1
res = 0
for n in range(2, order+2):
res += sign * x_n/fact
x_n *= x
fact *= n
sign = -sign
return res
for comparison (because this is the same function):
from math import exp
def real_funtion(x):
return 1-exp(-x)

Python pi calculation?

I am a python beginner and I want to calculate pi. I tried using the Chudnovsky algorithm because I heard that it is faster than other algorithms.
This is my code:
from math import factorial
from decimal import Decimal, getcontext
getcontext().prec=100
def calc(n):
t= Decimal(0)
pi = Decimal(0)
deno= Decimal(0)
k = 0
for k in range(n):
t = ((-1)**k)*(factorial(6*k))*(13591409+545140134*k)
deno = factorial(3*k)*(factorial(k)**3)*(640320**(3*k))
pi += Decimal(t)/Decimal(deno)
pi = pi * Decimal(12)/Decimal(640320**(1.5))
pi = 1/pi
return pi
print calc(25)
For some reason this code yields the vakue of pi up to only 15 decimals as compared with the acceptable value. I tried to solve this by increasing the precision value; this increases the number of digits, but only the first 15 are still accurate. I tried changing the way it calculates the algorithm and it didn't work either. So my question is, is there something that can be done to this code to make it much more accurate or would I have to use another algorithm? I would appreciate help with this because I don't know how to operate with so many digits in python. I would like to be able to control the number of (correct) digits determined and displayed by the program -- whether 10, 100, 1000, etc.
It seems you are losing precision in this line:
pi = pi * Decimal(12)/Decimal(640320**(1.5))
Try using:
pi = pi * Decimal(12)/Decimal(640320**Decimal(1.5))
This happens because even though Python can handle arbitrary scale integers, it doesn't do so well with floats.
Bonus
A single line implementation using another algorithm (the BBP formula):
from decimal import Decimal, getcontext
getcontext().prec=100
print sum(1/Decimal(16)**k *
(Decimal(4)/(8*k+1) -
Decimal(2)/(8*k+4) -
Decimal(1)/(8*k+5) -
Decimal(1)/(8*k+6)) for k in range(100))
For people who come here just to get a ready solution to get arbitrary precision of pi with Python (source with a couple of edits):
import decimal
def pi():
"""
Compute Pi to the current precision.
Examples
--------
>>> print(pi())
3.141592653589793238462643383
Notes
-----
Taken from https://docs.python.org/3/library/decimal.html#recipes
"""
decimal.getcontext().prec += 2 # extra digits for intermediate steps
three = decimal.Decimal(3) # substitute "three=3.0" for regular floats
lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24
while s != lasts:
lasts = s
n, na = n + na, na + 8
d, da = d + da, da + 32
t = (t * n) / d
s += t
decimal.getcontext().prec -= 2
return +s # unary plus applies the new precision
decimal.getcontext().prec = 1000
pi = pi()
from decimal import *
#Sets decimal to 25 digits of precision
getcontext().prec = 25
def factorial(n):
if n<1:
return 1
else:
return n * factorial(n-1)
def plouffBig(n): #http://en.wikipedia.org/wiki/Bailey%E2%80%93Borwein%E2%80%93Plouffe_formula
pi = Decimal(0)
k = 0
while k < n:
pi += (Decimal(1)/(16**k))*((Decimal(4)/(8*k+1))-(Decimal(2)/(8*k+4))-(Decimal(1)/(8*k+5))-(Decimal(1)/(8*k+6)))
k += 1
return pi
def bellardBig(n): #http://en.wikipedia.org/wiki/Bellard%27s_formula
pi = Decimal(0)
k = 0
while k < n:
pi += (Decimal(-1)**k/(1024**k))*( Decimal(256)/(10*k+1) + Decimal(1)/(10*k+9) - Decimal(64)/(10*k+3) - Decimal(32)/(4*k+1) - Decimal(4)/(10*k+5) - Decimal(4)/(10*k+7) -Decimal(1)/(4*k+3))
k += 1
pi = pi * 1/(2**6)
return pi
def chudnovskyBig(n): #http://en.wikipedia.org/wiki/Chudnovsky_algorithm
pi = Decimal(0)
k = 0
while k < n:
pi += (Decimal(-1)**k)*(Decimal(factorial(6*k))/((factorial(k)**3)*(factorial(3*k)))* (13591409+545140134*k)/(640320**(3*k)))
k += 1
pi = pi * Decimal(10005).sqrt()/4270934400
pi = pi**(-1)
return pi
print "\t\t\t Plouff \t\t Bellard \t\t\t Chudnovsky"
for i in xrange(1,20):
print "Iteration number ",i, " ", plouffBig(i), " " , bellardBig(i)," ", chudnovskyBig(i)

Categories