Calculating pi in python - Leibnitz - python

I am starting my adventure with Python. My current program is very simple, it has to calculate pi using Leibnitz formula, and stop working when module from "a" varibale is less than x. So far, it looks like this:
from math import fabs
from math import pi
x=float(input('Enter accuracy of calculating:'))
sum=0
a=0
n=0
while True:
a=float(((-1)**n)/(2*n+1))
sum+=a
n+=1
result=sum*4
if fabs(a)<x:
break
print('Calculated pi:',result)
print('Imported pi:', pi)
It looks ok, but here's the problem:
In my version of Geanie it works great, but on my friend's Geanie - it calculates 0.0.
Also, on Ideone.com (without keyboard input, just e.g. x=0.0001) it also returns 0.0.
Does anyone knows where the problem is?

Try this
a=((-1)**n)/float(2*n+1)
instead of this
a=float(((-1)**n)/(2*n+1))
Reason: I don't see a point to setting a itself to be a float, but setting the divisor or dividend in the division that produces a will ensure that Python doesn't cut the remainder (which is the default for integer division before Python 3.0).
Side issue: Your style doesn't match the official Python style guidelines, so you might want to change that.

Related

Basic Python code works differently on new machine (Mac)

I just started my new M1 MacBook and since Python2.7 is preinstalled, I wanted to run a little harmonic series program in the terminal to compare to my old Mac (old Intel). A silly test, I know.
import time
t_1=time.time()
x=1
i=1
while x<20:
i+=1
x+=1/i
if i % 1e6 == 0: print(i,x);
print(i)
t_2=time.time()
print(str(t_2-t_1)+' s')
It turned out that only on the M1 Mac the program was not running as expected, since x did not increase. I had to change x+=1/i to x+=1/float(i) so x was understood as a float and not 'rounded' to 1 (staying an int). I thought that, while the latter is actual the more correct way to program, python is flexible with variables, and my most important question is of course: Why does this work differently on different machines?
In python2.7 the / is integer division. If you import
from __future__ import division
at the top of your file, then you can use / for float division.
If you still want to be able to use integer division, you can always use //.

Raise Integers to negative integer powers in Python 2.7

I'm having a really hard time translating this Matlab code to Python.
I'll show you my effort so far.
This is the matlab code
Sigma=BW1/(2*(2*(-log(10^(att_bw/10)))^(1/Order))^(1/2))
Now I tried to used Python power operator as I studied earlier this morning **
My code is
BW1 = np.array([100])
att_bw = np.array([-3])
Order = np.array([1])
Sigma = BW1/(2*(2*(-np.log(10**(att_bw[0]/10)))**(1/Order))**(1/2))
However it says that it cannot handle negative powers unfortunately
The result for sigma should be 42.539
EDIT: it seems my code runs perfectly fine in Python 3. However I'm stuck with Python 2.7. So is there any easy way to port it?
In python2 you need to make sure you use floating point numbers. To make them so, add . after each integer you now have in your formula.
Like this:
import numpy as np
BW1 = np.array([100])
att_bw = np.array([-3])
Order = np.array([1])
Sigma = BW1/(2.*(2.*(-np.log(10.**(att_bw[0]/10.)))**(1./Order))**(1./2.))
print Sigma
Output
[42.53892736]

Sympy: Expanding sum that involves Kets from its quantum module

Today I started using sympy and its quantum module to implement some basic calculations in Bra-Ket notation.
Executing the code:
from sympy.physics.quantum import *
from sympy.physics.quantum.qubit import *
from sympy import *
from sympy.abc import k
print Sum(Ket(k),(k,0,5))
yields the expected result, that is, Sum(|k>, (k, 0, 5)) is printed.
Now I'd like to expand the sum and therefore write:
print Sum(Ket(k),(k,0,5)).doit()
However, this doesn't give the correct result, but prints out 6*|k> which obviously is not the desired output. Apparently, the program doesn't recognize Ket(k) as depending on the index k.
How could I work around or solve this issue?
Looks like a bug. You can probably work around it by doing the sum outside of sympy, with standard python functions like sum(Ket(i) for i in range(6)).

Floating point calculations debugging

So I recently decided to learn python and as a exercise (plus making something useful) I decided to make a Euler's Modified Method algorithm for solving higher-then-first order differential equations. An example input would be:
python script_name.py -y[0] [10,0]
where the first argument is the deferential equation (here: y''=-y), and the second one the initial conditions (here: y(0)=10, y'(0)=0). It is then meant to out put the resusts to two files (x-data.txt, and y-data.txt).
Heres the problem:
When in run the code with the specified the final line (at t=1) reads -0.0, but if you solve the ODE (y=10*cos(x)), it should read 5.4. Even if you go through the program with a pen and paper and execute the code, your (and the computers) results apart to diverge by the second iteration). Any idea what could have caused this?
NB: I'm using python 2.7 on a os x
Here's my code:
#! /usr/bin/python
# A higher order differential equation solver using Euler's Modified Method
import math
import sys
step_size = 0.01
x=0
x_max=1
def derivative(x, y):
d = eval(sys.argv[1])
return d
y=eval(sys.argv[2])
order = len(y)
y_derivative=y
xfile = open('x-data.txt','w+')
yfile = open('y-data.txt','w+')
while (x<x_max):
xfile.write(str(x)+"\n")
yfile.write(str(y[0])+"\n")
for i in range(order-1):
y_derivative[i]=y[(i+1)]
y_derivative[(order-1)] = derivative(x,y)
for i in range(order):
y[i]=y[i]+step_size*y_derivative[i]
x=x+step_size
xfile.close()
yfile.close()
print('done')
When you say y_derivative=y they are the SAME list with different names. I.e. when you change y_derivative[i]=y[i+1] both lists are changing. You want to use y_derivative=y[:] to make a copy of y to put in y_derivative
See How to clone or copy a list? for more info
Also see http://effbot.org/zone/python-list.htm
Note, I was able to debug this in IDLE by replacing sys.argv with your provided example. Then if you turn on the debugger and step through the code, you can see both lists change.

I keep on having problems with syntax and calculating the roots of the quadratic equation

Hey I am having problems with calculating the roots of the quadratic equation with the quadratic formula, using python's complex number functionality.
When I try
>>> if root<0:
root=abs(complex(root))
j=complex(0,1)
x1=(-b+sqrt(root))/2*a
x2=(-b-j+sqrt(root))/2*a
else:
I get the error message
SyntaxError: invalid syntax
Then, when I try instead
>>> if root<0:
root=abs(complex(root))
j=complex(0,1)
x1=(-b+j+sqrt(root))/2*a
x2=(-b-j+sqrt(root))/2*a
break
I get the error
SyntaxError: 'break' outside loop
I am trying to put:
else:
x1=(-b+j+sqrt(root))/2*a
x2=(-b-j+sqrt(root))/2*a
under it but it won't work.
Any help please?
Not sure I understand your problem, but it looks like you are not properly indenting -- Python uses white space to mark blocks, so the above should look like:
if root<0:
root=abs(complex(root))
j=complex(0,1)
x1=(-b+j+sqrt(root))/2*a
x2=(-b-j+sqrt(root))/2*a
else:
x1=(-b+j+sqrt(root))/2*a
x2=(-b-j+sqrt(root))/2*a
although that doesn't make sense because x1 and x2 are calculated the same in both branches, and j is not defined in the else branch... so maybe what you really want is
if root<0:
root=abs(complex(root))
j=complex(0,1)
x1=(-b+j+sqrt(root))/2*a
x2=(-b-j+sqrt(root))/2*a
Part of my confusion is the prompt: enter code here -- this is not a standard Python prompt so either you changed your prompt or you are using some other program with your Python. At any rate, hope this helps.
try importing the complex math module, available online in a number of forms. I believe there is an implementation for complex numbers in the standard python distributions, as well as in numpy/scipy. You can also try working out the real and complex components of your roots separately (by including a test based on the value of the discriminant). Also, your if and elif tests are identical.
As #bythenumbers points out, your if and elif conditions are the same. Also, are you getting exceptions or the wrong values? Also also, where you have j+sqrt(root), do you perhaps mean j*sqrt(root)?

Categories

Resources