Compute the value of π using the following series (Matlab conversion) - python

I just started using Python and can't really get the hang of it..
I wrote the code in Matlab but is hard to covert it the right way in Python.
Could you please help?
x=0;
for i=1:1000
x=x+(1/((((2*i)-1)^2)*(((2*i)+1^2))));
z=sqrt((x*16)+8);
error=abs(z-pi);
if (error < 10^-8)
i
break
end
end
Thank you

The following segment of code is equivalent to what you have written in Matlab.
from math import pi, sqrt
x = 0
error_tolerance = 1e-8
for i in range(1, 1001):
x += 1 / (((2 * i - 1) ** 2) * ((2 * i + 1) ** 2))
z = sqrt((x * 16) + 8)
error = abs(z - pi)
if error < error_tolerance:
print(i)
break
The key differences in between Python and Matlab that can be seen in this code are:
Indentation: For loops, while loops, if statements, function definitions, etc. are isolated using correct indentation instead of a starting keyword and end. You can see that the for loop statement ends with a colon, and everything inside the for loop has been indented by a tab OR 4 spaces. The break keyword is further indented because it only executes when the error is less than the specified tolerance.
Operators: You can see that the raised power symbol ^ has been replaced with **. This is because ^ represents a bitwise XOR operation. You may also notice that x += ... has been used instead of x = x + .... These two statements are equivalent, the first way is just more concise.
Semicolons: Python does not require the use of semicolons to mute a variable/constant. Instead, to find out what the value of the variable is, simply use the print(...) statement.
For loops: Instead of just iterating over a linear sequence like Matlab does, in Python each for loop will iterate over the next item in a specified iterable sequence. In this case, we have used the built-in range function to generate a list of integers from 1 to 1000, and in each loop i will be set to the next value in this linear sequence.
Non built-in functions: Python's base set of built-ins does not contain a sqrt function or pi constant definition. Instead these have been separated into a separate module named math alongside many other mathematical functions such as sin, cosine, etc..
Brackets around if-conditions: You can use brackets around if statement conditions. However, for simple conditions such as this one, they are not necessary.
There are many more differences between the two languages, I have just highlighted the most noticeable differences between the Matlab code you have provided and its Python equivalent. To find out more about Python I suggest looking at online tutorials, and you can find plenty of answers to commonly asked questions through a Google search or on this site.
Edit: I noticed a slight error in your implementation of the mathematical sequence, and have updated it to match the formula provided in your link. I also removed unnecessary brackets

import math
...
x = 0
for i in range(1,1001):
x = x + (1 / (((2 * i - 1) ** 2) * ((2 * i + 1) ** 2)))
z = math.sqrt((x * 16) + 8)
error = abs(z - math.pi)
if error < 10 ** -8:
print(i)
break

Related

Anyway to get rid of `math.floor` for positive odd integers with `sympy.simplify`?

I'm trying to simplify some expressions of positive odd integers with sympy. But sympy refuses to expand floor, making the simplification hard to proceed.
To be specific, x is a positive odd integer (actually in my particular use case, the constraint is even stricter. But sympy can only do odd and positive, which is fine). x // 2 should be always equal to (x - 1) / 2. Example code here:
from sympy import Symbol, simplify
x = Symbol('x', odd=True, positive=True)
expr = x // 2 - (x - 1) / 2
print(simplify(expr))
prints -x/2 + floor(x/2) + 1/2. Ideally it should print 0.
What I've tried so far:
Simplify (x - 1) // 2 - (x - 1) / 2. Turns out to be 0.
Multiply the whole thing by 2: 2 * (x // 2 - (x - 1) / 2). Gives me: -x + 2*floor(x/2) + 1.
Try to put more weights on the FLOOR op by customizing the measure. No luck.
Use sympy.core.evaluate(False) context when creating the expression. Nuh.
Tune other parameters like ratio, rational, and play with other function like expand, factor, collect. Doesn't work either.
EDIT: Wolfram alpha can do this.
I tried to look like the assumptions of x along with some expressions. It surprises me that (x - 1) / 2).is_integer returns None, which means unknown.
I'm running out of clues. I'm even looking for alternativese of sympy. Any ideas guys?
I fail to see why sympy can't simplify that.
But, on another hand, I've discovered the existence of odd parameter just now, with your question.
What I would have done, without the knowledge of odd is
k = Symbol('k', positive=True, integer=True)
x = 2*k-1
expr = x // 2 - (x - 1) / 2
Then, expr is 0, without even the need to simplify.
So, can't say why you way doesn't work (and why that odd parameter exists if it is not used correctly to guess that x-1 is even, and therefore (x-1)/2 integer). But, in the meantime, my way of defining an odd integer x works.
There is some reluctance to make too much automatic in SymPy, but this seems like a case that could be addressed (since (x-1)/2 is simpler than floor(x/2). Until then, however, you can run a replacement on your expression which makes this transformation for you.
Let's define a preferred version of floor:
def _floor(x):
n, d = x.as_numer_denom()
if d == 2:
if n.is_odd:
return (n - 1)/2
if n.is_even:
return n/2
return floor(x)
When you have an expression with floor that you want to evaluate, replace floor with _floor:
>>> x = Symbol('x', odd=True)
>>> eq=x // 2 - (x - 1) / 2
>>> eq.replace(floor, _floor)
0

Implementing a function defined by double infinite sums in python

I want to implement a python function that evaluates a mathematical function (of four variables) defined by a double infinite sum at a particular point.
I've done this by using
def myfunction(x):
value = 0.0
for m in range(1,100):
for n in range(1,100):
value = value + 4.0*(1.0/((n + m)*np.pi**5)) * np.sin(n*x.detach().numpy()[:, 0:1]) * np.sin(m**2 * x.detach().numpy()[:, 1:2]) * np.sin(n*np.pi*x.detach().numpy()[:, 2:3])* np.cos(m*2*x.detach().numpy()[:, 3:4])
return torch.from_numpy(value)
Is there a better (more efficient) way to do this? When I call this function, it runs very slowly (and I'm only summing indices up to 100).

While solving a cubic equation, how do I divide a cubic polynomial by a linear one (Python 3)?

I'm making a solver of cubic equations in Python that includes division of polynomials.
from sympy import symbols
# Coefficients
a = int(input("1st coef: "))
b = int(input("2nd coef: "))
c = int(input("3rd coef: "))
d = int(input("Const: "))
# Polynomial of x
def P(x):
return a*x**3 + b*x**2 + c*x + d
x = symbols('x')
# Find 1 root by Cardano
R = (3*a*c - b**2) / (9*a**2)
Q = (3*b**3 - 9*a*b*c + 27*a**2*d) / (54*a**3)
Delta = R**3 + Q**2
y = (-Q + sqrt(Delta))**(1/3) + (-Q - sqrt(Delta))**(1/3)
x_1 = y - b/(3*a)
# Division
P(x) / (x - x_1) = p(x)
print(p(x)) # Just a placeholder
The program returns an error: "cannot assign to operator" and highlights the P(x) after the # Division comment (worded poorly, yes, but I'm from Russia so idc).
What I tried doing was to assign a variable to a polynomial and then dividing:
z = P(x)
w = x - x_1
p = z / w
print(p)
But alas: it just returns a plain old quotient (a = 1, b = 4, c = -9, d = -36):
(x**3 + 4*x**2 - 9*x - 36)/(x - 2.94254537742264)
Does anyone out here knows what to do in this situation (not to mention the non-exact value of x_1: the roots of x^3+4x^2-9x-36=0 are 3, -4, and -3, no floaty-irrational-messy-ugly things in sight)?
tl;dr: Polynomial division confusion and non-exact roots
I am not sure what exactly your question is but here is an attempt at an answer
The line
P(x) / (x - x_1) = p(x)
is problematic for multiple reasons. First of all it's important to know that the = operator in python (and a lot of other modern programming languages) is an assignment operator. You seem to come from more of a math background, so consider it to be something like the := operator. The direction of this is always fixed, i.e. with a = b you are always assigning the value of b to the variable a. In your case you are basically assigning an expression the value of p which does not make much sense:
Python can't assign anything to an expression (At least not as far as I know)
p(x) is not yet defined
The second problem is that you are mixing python functions with math functions.
A python function looks something like this:
def some_function(some_parameter)
print("Some important Thing!: ", some_parameter)
some_return_value = 42
return some_return_value
It (can) take some variable(s) as input, do a bunch of things with them, and then (can) return something else. They are generally called with the bracket operator (). I.e. some_function(42) translates to execute some_function and substitute the first parameter with the value 42. An expression in sympy however is as far as python is concerned just an object/variable.
So basically you could have just written P = a*x**3 + b*x**2 + c*x + d. What your P(x) function is doing is basically taking the expression a*x**3 + b*x**2 + c*x + d, substituting x for whatever you have put in the brackets, and then giving it back in as a sympy expression. (It's important to understand, that the x in your P python function has nothing to do with the x you define later! Because of that, one usually tries to avoid such "false friends" in coding)
Also, a math function in sympy is really just an expression formed from sympy symbols. As far as sympy is concerned, the return value of the P function is a (mathematical) function of the symbols a,b,c,d and the symbol you put into the brackets. This is why, whenever you want to integrate or differentiate, you will need to specify by which symbol to do that.
So the line should have looked something like this.
p = P(x) / (x - x_1)
Or you leave replace the P(x) function with P = a*x**3 + b*x**2 + c*x + d and end up with
p = P / (x - x_1)
Thirdly if you would like to have the expression simplified you should take a look here (https://docs.sympy.org/latest/tutorial/simplification.html). There are multiple ways here of simplifying expressions, depending on what sort of expression you want as a result. To make for faster code sympy will only simplify your expression if you specifically ask for it.
You might however be disappointed with the results, as the line
y = (-Q + sqrt(Delta))**(1/3) + (-Q - sqrt(Delta))**(1/3)
will do an implicit conversion to floating point numbers, and you are going to end up with rounding problems. To blame is the (1/3) part which will evaluate to 0.33333333 before ever seeing sympy. One possible fix for this would be
y = (-Q + sqrt(Delta))**(sympy.Rational(1,3)) + (-Q - sqrt(Delta))**(sympy.Rational(1,3))
(You might need to add import sympy at the top)
Generally, it might be worth learning a bit more about python. It's a language that mostly tries to get out of your way with annoying technical details. This unfortunately however also means that things can get very confusing when using libraries like sympy, that heavily rely on stuff like classes and operator overloading. Learning a bit more python might give you a better idea about what's going on under the hood, and might make the distinction between python stuff and sympy specific stuff easier. Basically, you want to make sure to read and understand this (https://docs.sympy.org/latest/gotchas.html).
Let me know if you have any questions, or need some resources :)

Need to create function in Python that finds all complex and real roots of z^n=x(so the nth-roots of x)

beginner programmer here. I have been assigned to create a function 'Roots' that takes two parameters x and n(n has to be an integer) and then calculates all complex and real roots of the equation z^n=x. However, the only module/package I can use is math. Also, I have been told that the certain aspects of the following function 'Power_complex' play a big role into creating 'Roots':
def Power_complex(re, im, n): #calculates the n-th power of a complex number(lets call this a), where 're' is the real part and 'im' the imaginary part
import math
r=math.sqrt((re)**2+(im)**2) #calculates modulus
h=math.atan2(re,im) #calculates argument(angle)
ren=(r**n)*math.cos(h*n) #calculates the real part of a^n
imn=(r**n)*math.sin(h*n) #calculates the imaginary part of a^n
return ren, imn
print '(',re, '+', im, 'i',')','^',n,'=',ren,'+',imn,'i' #displays the result
Also, I need to somehow implement a for loop into 'Roots'.
I have been pondering over this for hours, but alas I really can't figure it out and am hoping one of you can help me out here.
BTW my python version is 2.7.10
The expression for the solutions is ( explained here ):
when
In the case that z^n is real, equal to the x in your question, then r = |x| and the angle is 0 or pi for positive and negative values, respectively.
So you make the modulus and argument as you have done, then make every solution corresponding to a value of k
z = [r**(1./n) * exp(1j * (theta + 2*pi*k) / n ) for k in range(n)]
This line uses a Python technique called list comprehension. An eqvivalent way of doing it (that you may be more familiar to) could be:
z = []
for k in range(n):
nthroot = r**(1./n) * exp( 1j * (theta + 2*pi*k) / n )
z.append(nthroot)
Printing them out could be done in the same fashion, using a for-loop:
for i in range(len(z)):
print "Root #%d = %g + i*%g" % (i, z[i].real, z[i].imag)
Note that the exp-function used must be from the module cmath (math can't handle complex numbers). If you are not allowed to use cmath, then I suggest you rewrite the expression for the solutions to the form without modulus and argument.

fixed point iteration algorithm

I am asked to write a program to solve this equation ( x^3 + x -1 = 0 ) using fixed point iteration.
What is the algorithm for fixed point iteration?
Is there any fixed point iteration code sample in Python? (not a function from any modules, but the code with algorithms)
Thank You
First, read this:
Fixed point iteration:Applications
I chose Newton's Method.
Now if you'd like to learn about generator functions, you could define a generator function, and instance a generator object as follows
def newtons_method(n):
n = float(n) #Force float arithmetic
nPlusOne = n - (pow(n,3) + n - 1)/(3*pow(n,2) +1)
while 1:
yield nPlusOne
n = nPlusOne
nPlusOne = n - (pow(n,3) + n - 1)/(3*pow(n,2) +1)
approxAnswer = newtons_method(1.0) #1.0 can be any initial guess...
Then you can gain successively better approximations by calling:
approxAnswer.next()
see: PEP 255 or Classes (Generators) - Python v2.7 for more info on Generators
For example
approx1 = approxAnswer.next()
approx2 = approxAnswer.next()
Or better yet use a loop!
As for deciding when your approximation is good enough... ;)
Pseudocode is here, you should be able to figure it out from there.

Categories

Resources