After my blunder with the infinity factorial sum XD I redid the code, but I keep getting syntax error :\
from scitools.std import *
from math import factorial, cos, e
from scipy import *
import numpy as np
def f1(t):
return 0.5*(1 + sum( (a**(2*n)*cos(2*sqrt(1 + n)*t))/(e**a**2*factorial(n)) for n in range(0,100)))
a=4
t = linspace(0, 35, 1000)
y1 = f1(t)
plot(t, y1)
xlabel(r'$\tau$')
ylabel(r'P($\tau$)')
legend(r'P($\tau$)')
axis([0.0, 35.0, 0.0, 1.0])
grid(True)
show()
It says that there's an error in my program: invalid syntax and the a is red :\
What's wrong now? :(
EDIT:
I've added another ) at the end of the sum, but now I keep getting huge error:
Traceback (most recent call last):
File "D:\faxstuff\3.godina\kvantna\vježbe\qm2\v8\plot.py", line 12, in <module>
y1 = f1(t)
File "D:\faxstuff\3.godina\kvantna\vježbe\qm2\v8\plot.py", line 8, in f1
return 0.5*(1 + sum( (a**(2*n)*cos(2*sqrt(1 + n)*t))/(e**a**2*factorial(n)) for n in range(0,100)))
File "C:\Python26\lib\site-packages\numpy\core\fromnumeric.py", line 1415, in sum
res = _sum_(a)
File "D:\faxstuff\3.godina\kvantna\vježbe\qm2\v8\plot.py", line 8, in <genexpr>
return 0.5*(1 + sum( (a**(2*n)*cos(2*sqrt(1 + n)*t))/(e**a**2*factorial(n)) for n in range(0,100)))
TypeError: unsupported operand type(s) for /: 'numpy.ndarray' and 'numpy.float64'
Should I make so that the sum expression gives back an array from which I can plot or?
The parentheses in return 0.5*(1 + sum(... are not balanced.
As a matter of style, I would recommend avoiding from <module> import *-style imports. In your specific example you end up with a single-letter variable name (e) imported into the global namespace, which you then proceed to use. This could lead to confusion and, worse, hard-to-diagnose bugs.
Related
I want to plot a function in python but I can't seem to do it. I am running the following code, but I get an error that says I can't multiply a generator and a float together. Where is this coming from?
from math import *
import matplotlib.pyplot as plt
t=0.1
cd=t*exp(-t/2)
tau=10
nt=100
v=0.01
w=0.9
u=0.4
s0=10
p=5
for i in range (1,10):
sigma= u/(w+(s0/(p*cd)))
print(sigma)
C= lambda ksi: cd * (1-exp(((u-w * sigma)/v)*ksi))
plt.plot([-10,-9,-8,-7,-6,-5,-4,-3,-2,-1],[C(i for i in range (-10,-1))])
plt.xlabel(ksi)
plt.ylabel(concentration)
plt.title("tumeur avec regénessence")
plt.legend()
plt.show()
t+=tau/nt
this is the error I get
Traceback (most recent call last):
File "C:\Users\ilyes\Downloads\tumeur_avec_regénesence.py", line 18, in <module>
plt.plot([-10,-9,-8,-7,-6,-5,-4,-3,-2,-1],[C(i for i in range (-10,-1))])
File "C:\Users\ilyes\Downloads\tumeur_avec_regénesence.py", line 17, in <lambda>
C= lambda ksi: cd * (1-exp(((u-w * sigma)/v)*ksi))
TypeError: unsupported operand type(s) for *: 'float' and 'generator'
use
plt.plot([-10,-9,-8,-7,-6,-5,-4,-3,-2,-1],[C(i) for i in range (-10, 0)])
instead of
plt.plot([-10,-9,-8,-7,-6,-5,-4,-3,-2,-1],[C(i for i in range (-10,-1))])
explanation: you want to apply C on each value not on the hole list at once.
range(-10,-1) gives you values -10 <= v < -1 but you want -1 to be included.
Use numpy.
import numpy as np
import matplotlib.pyplot as plt
tau=10
nt=100
v=0.01
w=0.9
u=0.4
s0=10
p=5
ksi = np.arange(-10,0)
for t in np.arange(1,10)*tau/nt:
cd = t*np.exp(-t/2)
sigma = u/(w+(s0/(p*cd)))
C = lambda ksi: cd * (1-np.exp(((u-w * sigma)/v)*ksi))
plt.plot(ksi, C(ksi), label=f"t = {t}")
plt.xlabel("ksi")
plt.ylabel("concentration")
plt.title("tumeur avec regénessence")
plt.legend()
plt.show()
For my course in Python, I am creating a program that calculates the distance between two cities bases on their coordinates. It has worked and suddenly I got the following error:
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
distance(+1, 52, 22, +1, 4, 32, +1, 45, 30, -1, 73, 35)
File "C:/Python27/flying_distances_1.py", line 26, in distance
distance = Haversine(lat_1, lat_2, lon_1, lon_2) * 6367.0
File "C:/Python27/flying_distances_1.py", line 4, in Haversine
a_1 = math.sin((lat_2 - lat_1)/2) ** 2
TypeError: unsupported operand type(s) for -: 'NoneType' and 'NoneType'
This is the code that goes with it:
import math
def Haversine (lat_1, lat_2, lon_1, lon_2):
a_1 = math.sin((lat_2 - lat_1)/2) ** 2
a_2 = math.cos(lat_1) * math.cos(lat_2)
a_3 = math.sin((lon_2-lon_1)/2) ** 2
a_4 = a_1 + a_2 * a_3
b = 1 - a_4
d = 2 * math.atan2(math.sqrt(a_4), math.sqrt(b))
def conversion (sign, degrees, minutes):
minutes_to_degrees = 1/60.0 * minutes
total_degrees = minutes_to_degrees + degrees
radians = total_degrees * 1/180.0 * math.pi
total_radians = sign * radians
def distance (sign_lat_1, deg_lat_1, min_lat_1,
sign_lon_1, deg_lon_1, min_lon_1,
sign_lat_2, deg_lat_2, min_lat_2,
sign_lon_2, deg_lon_2, min_lon_2):
lat_1 = conversion(sign_lat_1, deg_lat_1, min_lat_1)
lon_1 = conversion(sign_lon_1, deg_lon_1, min_lon_1)
lat_2 = conversion(sign_lat_2, deg_lat_2, min_lat_2)
lon_2 = conversion(sign_lon_2, deg_lon_2, min_lon_2)
distance = Haversine(lat_1, lat_2, lon_1, lon_2) * 6367.0
return distance
I have searched and searched but I can't seem to find the error that causes the aforementioned message in my code. It probably is something really small (and possibly quite stupid ;)), but the person that can find the error will help me back on track!
There is no return statement in the conversion function. At the moment, the radians value is calculated then forgotten when the function finishes. If you want the value of total_radians to be accessed from outside the function, add
return total_radians
as the last line of the conversion function.
I’m having trouble using the bisect optimizer within scipy. Here are the relevant portions of my code:
How I’m importing things
import numpy as np
import scipy.optimize as sp
import matplotlib.pyplot as plt
Break in code, section causing errors below
#All variables are previously defined except for h
def BeamHeight(h):
x = 1000e3*M[i]*h/(fw*h^3-(fw-wt)(h-2*ft)^3) - Max_stress_steel
return x
for i in range(0,50):
h = np.zeros((50))
h[i] = sp.bisect(BeamHeight, hb, 5,xtol = 0.001)
Causing this error:
Traceback (most recent call last):
File "ShearMoment.py", line 63, in <module>
h[i] = sp.bisect(BeamHeight, hb, 5,xtol = 0.001)
File "/usr/lib/python2.7/dist-packages/scipy/optimize/zeros.py", line 248, in bisect
r = _zeros._bisect(f,a,b,xtol,rtol,maxiter,args,full_output,disp)
File "ShearMoment.py", line 58, in BeamHeight
x = 1000e3*M[i]*h/(fw*h^3-(fw-wt)(h-2*ft)^3) - Max_stress_steel
TypeError: 'float' object is not callable
I understand that scipy.optimize expects a function as one of its arguments. Am I doing this incorrectly?
In Python, concatenation is not implicitly multiplication, and ^ is not exponentiation. Multiplication must be made explicit with *, and exponentiation must be written as **. This part of BeamHeight:
fw*h^3-(fw-wt)(h-2*ft)^3
must be written as
fw*h**3-(fw-wt)*(h-2*ft)**3
I try to approximate triple integral ∫∫∫xyzdV , where S=[0,1]×[0,1]×[0,1] using Monte Carlo method.
I have this code:
from numpy import *
import time
from scipy.integrate import tplquad
numpoints=100000 # number of random sample points
I2d=0.0 # initialize value
I2dsquare=0.0 # initialize to allow for calculation of variance
for n in xrange(numpoints):
x=random.uniform()
y=random.uniform()
z=random.uniform()
func = lambda x,y,z: x*y*z
x1,x2 = 0, 1
y1,y2 = lambda x: 0,lambda x: 1
z1,z2 = lambda x, y: 0,lambda x, y: 1
I2d += tplquad(func, x1,x2,y1,y2,z1,z2)
I2dsquare += (tplquad(func, x1,x2,y1,y2,z1,z2))**2
I2d=I2d/numpoints
I2dsquare=I2dsquare/numpoints
EstimError=4*sqrt( (I2dsquare - I2d**2)/numpoints) # estimated error
I2d=4*I2d
print "Value: %f" %I2d
print "Error estimate: %f" %EstimError
And I have this error:
Traceback (most recent call last): for n in xrange(numpoints):
File "", line 1, in <module>
File "/tmp/tmpx_9bf5/___code___.py", line 17, in <module>
I2d += tplquad(func, x1,x2,y1,y2,z1,z2)
File "element.pyx", line 999, in sage.structure.element.ModuleElement.__iadd__ (sage/structure/element.c:8285)
File "coerce.pyx", line 797, in sage.structure.coerce.CoercionModel_cache_maps.bin_op (sage/structure/coerce.c:7467)
TypeError: unsupported operand parent(s) for '+': 'Real Field with 53 bits of precision' and '<type 'tuple'>'
I understand that there is different types in this code but I do not understand how to fix it. If I try to do this code for quadratic equation, for example, everything is OK but integral unfortunately do not work.
Look here: https://docs.scipy.org/doc/scipy-0.15.1/reference/generated/scipy.integrate.tplquad.html
scipy.integrate.tplquad returns a tuple (y, abserr).
I think you want this:
I2d += tplquad(func, x1,x2,y1,y2,z1,z2)[0]
(I don't completely understand this problem mathematically so I hope it's not wrong.)
I was trying to fit a specific function with scipy and I got weird results. I decided to test something I know the answer to so I created this:
from scipy.optimize import curve_fit as cf
import numpy as np
import random
def func(x,a):
return a+X
X =[]
for i in range (10):
V = random.random()
X.append(i+3 + V/10)
print cf(func, np.array(range(10)),np.array(X))
I expected to get something around 3, nevertheless, here the output:
(array([ -2.18158824e-12]), inf)
As a side note, I tried to see what I send something to func and I got this:
print func(np.array(range(10)),3)
Traceback (most recent call last):
File "/tmp/py1759O-P", line 16, in <module>
print func(np.array(range(10)),3)
File "/tmp/py1759O-P", line 6, in func
return a+X
TypeError: unsupported operand type(s) for +: 'int' and 'list
What am I doing wrong?
Don't use x and X as variable names when they carry such different meanings (or perhaps you didn't know Python is case sensitive?):
def func(x,a):
return a+X
X =[]
x is a numpy array, X is a list, and a is a scalar parameter value.
a+X results in an error since you can not add a scalar to a list.
In func, the argument is x, but X is used in the body of the function.
Here's a modified version of your code. It uses a few more features of numpy (e.g. np.random.random() instead of random.random()).
from scipy.optimize import curve_fit as cf
import numpy as np
def func(x, a):
return a + x
n = 10
xdata = np.arange(n)
ydata = func(xdata, 3) + np.random.random(n) / 10
print cf(func, xdata, ydata)
The output is
(array([ 3.04734293]), array([[ 8.19208558e-05]]))