Unsupported operand types 'NoneType' - python

I am very new to Python, and I'm trying to create a software that calculates a series of equations and I keep running into an error.
This is the code:
import math
x_i = 1
dt = 0.01
k = 11.5
r_out = 0.889
w = 0.03175
dL = 30
m = float(input("Enter m: "))
v_i = float(input("Enter v_i: "))
t = [0]
x = [x_i]
v = [v_i]
Fc = []
while (v_i > 0):
Fc.append(k*v_i**2*math.cos(math.atan(30/x_i)))/2*(math.sqrt(r_out**2-(w/math.pi)*math.sqrt(x_i**2+dL**2)))
x.append(x_i+v_i*Dr+0.5*(-Fc_I/m)*dt)
v.append(v_i-(k*v_i**2*math.cos(math.atan(30/x_i)))/2*(math.sqrt(r_out**2-(w/math.pi)*math.sqrt(x_i**2+dL**2))))
v_i = v_i + 1
t.append(dt*(t+1))
My goal is that the code runs these equations until v_i equals 0, while populating the lists with the relevant results, then throwing all the information into a graph once the while loop is done.
However, after inserting m and v_i, I get an error that says:
line 19, in <module>
FC.append(k*v_i**2*math.cos(math.atan(30/x_i)))/2*(math.sqrt(r_out**2-(w/math.pi)*math.sqrt(x_i**2+dL**2)))
TypeError: unsupported operand type(s) for /: 'NoneType' and 'int'
I'm a bit stuck at the moment and I can't seem to figure out how to fix this error.

This line:
C.append(k*v_i**2*math.cos(math.atan(30/x_i)))/2*(math.sqrt(r_out**2-(w/math.pi)*math.sqrt(x_i**2+dL**2)))
You are appending a value to C, and then using the / operator on the append() call.
list.append() returns None, hence the error. Try this instead:
C.append(k*v_i**2*math.cos(math.atan(30/x_i))/2*(math.sqrt(r_out**2-(w/math.pi)*math.sqrt(x_i**2+dL**2))))
P.S. PEP-8 is recommended:
C.append(k * v_i ** 2 * math.cos(math.atan(30 / x_i)) / 2 * (math.sqrt(r_out ** 2 - (w / math.pi) * math.sqrt(x_i ** 2 + dL ** 2))))

You are closing the parenthesis before dividing it by 2, which is leading to NoneType.
Replace the line with-
Fc.append(k*v_i**2*math.cos(math.atan(30/x_i))/2*(math.sqrt(r_out**2-(w/math.pi)*math.sqrt(x_i**2+dL**2)))

Related

TypeError: 'numpy.ndarray' object is not callable, TypeError: unsupported operand type(s) for /: 'int' and 'list'

So basically I have multiple arrays and I need to calculate something with these arrays. The problem is that some of these arrays sometimes equal zero and are divisors.
I want to solve this problem by filtering my array and saying something like "if r >= rs: print("0"), else: print(H)", but it doesn't work. I also tried using map function to say that if the radius r < 0.00001: result = 0.00001, else: result = r.
I tried printing list(map(.....)), but it didn't work
def Max(r):
if r < 0.00001:
result = 0.00001
else:
result = r
return(result)
# radius array (trying to apply Max to all r)
r22 = map(Max, zz[:, 1]) # zz is an odeint function defined before
def Hamiltonian(r, pt, pr, pphi): #all values are given in the code
H = (-((1-rs/r)*-1)(pt*2)/2 + (1-rs/r)(pr*2)/2 + (pphi2)/(2(r**2)))
return(H)
I got three error messages, "TypeError: unsupported operand type(s) for /: 'int' and 'map'", "TypeError: 'numpy.ndarray' object is not callable", and TypeError: unsupported operand type(s) for /: 'int' and 'list'. Does anyone know why? Ideally, I'd like H to automatically print 0 for all the radius = 0 and ignore the division by zero. Can anyone please help me??
Your "H formula" is not correctly written, some multiplier signs are missing I believe...
H = (-((1-rs/r)*-1)*(pt*2)/2 + (1-rs/r)*(pr*2)/2 + (pphi*2)/(2*(r**2)))
For the division, you can try to handle an exception? Something like:
def hamiltonian(r, pt, pr, pphi):
while True:
try:
H = (-((1 - rs / r) * -1) * (pt * 2) / 2 + (1 - rs / r) * (pr * 2) / 2 + (pphi * 2) / (2 * (r ** 2)))
return(H)
except ZeroDivisionError:
H = 0
return(H)
print(hamiltonian(r, pt, pr, pphi))
check this to learn about handling of errors and exceptions

I'm getting this error but I tried everything. TypeError: can't multiply sequence by non-int of type 'float'

I'm having an issue with running this simple calculator. Every time I run this program, I get this error:
f = a * l
TypeError: can't multiply sequence by non-int of type 'float'
Does anyone notice my error and how I can correct it?
while True:
print("///Calculator///")
print("======================================")
mq = float(input("Market Quote: "))
if mq==0:
break
a = input("Balance: ")
l = input("Lev: ")
if not l:
l = 500
else:
l = float(l)
0
p = input("Other: ")
if not p:
p = 70
else:
p = float(p)
#-------------------------------------
f = a * l
q = f / l
mr = q * mq
so = 0.40
mm = mr * so
k = p * 10
b = a - mm
x = b / k
h = x / 8
u = round(h, 2)
o = x * mq
j = o / l
c = round(j)
You need to convert all numerical inputs to floats or ints if you want to do numerical calculations on them. You forgot a and p:
a = float(input("Balance: "))
...
p = float(input("Other: "))
Two general tips for the future: give your variables meaningful names (you can skip vowels or whatever for speed, but apart from indexes, one letter variables aren't great) and read error messages! Here 'can't multiply sequence by non-int of type 'float'' means exactly that! The result of any call to input() is a string (a sequence type) and when you multiply a sequence by an integer, Python interprets that as you wanting to repeat it, as in:
>>> 'a' * 4
'aaaa'
But what is it supposed to do with a float? I certainly don't know and neither does it:
>>> 'a' * 4.0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't multiply sequence by non-int of type 'float'
And if the worst comes to the worst and you can't interpret Python's complaints, then you still have the line number - go there and see that all that is being done is: f = a * l so your next step should be to analyse what are a, what are l and why can't Python multiply them!
My point is, yes debugging is hard, but it is a skill, and trying things isn't always the right way to go - sometimes being methodical speeds up the process.

Python 3 recognized an element as a string

I'm defining a loss function L(X,Y,c,b,d), where X and Y should be arrays, and c, b, d are floats. Here are my codes:
def L(X,Y,c,b,d):
error=0
a=Y[0]
for i in range(len(X)):
error = error + ((c*X[i]+(a/b)*np.sqrt(b**2-X[i]**2)+d)-Y[i])**2
return error
I'm getting
"TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'",
which seems to mean that python recognized X[i] as a string. What should I do?
Here are the full code, and X is a column of numbers.
def L(X,Y,c,b,d):
error=0
a=Y[0]
for i in range(len(X)):
error = error + ((c*X[i]+(a/b)*np.sqrt(b**2-X[i]**2)+d)-Y[i])**2
return error
def L_prime_c(X,Y,c,b,d):
p=0
for i in range(len(X)):
p=p+2*L(X,Y,c,b,d)*X[i]
return p
def L_prime_d(X,Y,c,b,d):
r=0
for i in range(len(X)):
r=r+2*L(X,Y,c,b,d)
return r
def fit(X,Y,learning_rate=1e-3,max_iter=20000,epsilon=1e-5):
c=1
b=1
d=Y[0]
for i in range(max_iter):
gradient_c = L_prime_c(X,Y,c,b,d)
c_new = c - learning_rate * gradient_c
gradient_b = L_prime_b(X,Y,c,b,d)
b_new = b - learning_rate * gradient_b
gradient_d = L_prime_d(X,Y,c,b,d)
d_new = d - learning_rate * gradient_d
if np.abs(c_new - c) < epsilon and np.abs(d_new - d) < epsilon and np.abs(b_new - b) < epsilon:
break
c=c_new
b=b_new
d=d_new
return np.array([c,b,d])
#getting X, Y
In = xlrd.open_workbook(r'C:\Users\gris_\Desktop\calculation4.xlsx')
isheet = In.sheet_by_name('Sheet1')
X=isheet.col_values(0)
Y=isheet.col_values(1)
a=Y[0]
#Calculation & Output
result=fit(X,Y,learning_rate=1e-3,max_iter=20000,epsilon=1e-5)
Problem solved: I have 6 columns of different length, so when reading data from one column, python actually adds these " to make shorter ones the same length as the longest one. When I delete the other columns, things work out fine. Many thanks for your help! :D
Seeing the code you just added, try to rewrite X,Y like this:
X=list(map(float,isheet.col_values(0)))
Y=list(map(float,isheet.col_values(1)))
Another: Your function can be simplified as a sum of all errors instead.
import numpy as np
# Another way of writing it
#def L(X,Y,c,b,d):
# error=0
# a=Y[0]
# for x,y in zip(X,Y):
# error += ((c*x+(a/b)*np.sqrt(b**2-x**2)+d)-y)**2
# return error
# Or even better:
def L(X,Y,c,b,d):
a = Y[0]
error = sum(((c*x+(a/b)*np.sqrt(b**2-x**2)+d)-y)**2 for x,y in zip(X,Y))
return error
X = [2.2,2.2,3.2]
Y = [2.0,2.1,3.1]
c = 1
b = 20
d = 1
print(L(X,Y,c,b,d))
Returns: 29.148285465180138
Where as, chaning X and Y to:
X = [2.2,2.2,3.2,'a']
Y = [2.0,2.1,3.1,'b']
Returns: TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'

Assigning the last iterated value to a variable in python

I have the last set of values of an iteration: y1[i],y2[i],y3[i](which was obtained by doing the integration of coupled ODE)
Now I need to assign these values to another variables : Y1,Y2,Y3 and then use these variables in a function f(y,t) (ODEs that has to be integrated again).
This is part of my code:
#constants used
H = 2.27e-18
l = 1.5
G = 6.637*(10**(-11))
k = (8*3.14*G)**0.5
om_de = 0.75
omega_matter = 1 - om_de
w0 = -0.85
rho_c = 3*(H**2)/(k**2)
c = ((om_de*(1 + w0)*rho_c)/(H**2))**0.5
v0 = (om_de*(1 - w0)*rho_c)/(2*np.exp(-l*k))
#for iteration
p = 0.0
q = 1.0
n = 10000.0
def H(Y1,Y2,Y3):
return -3*Y3*(H**2)*(omega_matter/(Y1**3) + (H**2)*(Y3**2)/(2.0*rho_c) + (v0*np.exp(-l*Y2*k))/(rho_c))**0.5 + (l*k*v0*np.exp(-l*Y2*k))/(H**2)
dH = (q-p)/n
Y1 = [y1[j]]
Y2 = [y2[j]]
Y3 = [y3[j]]
But I am not able to do any further operations on them.
TypeError: unsupported operand type(s) for ** or pow(): 'function' and
'int'
keeps showing up.
The link to the complete code is here:
https://pastebin.com/mdQE29N9 (might help in understanding what I am trying to achieve and the code is too lengthy to be posted here)
I think the problem is with the way I have assigned the values,but am not so sure. Any help here as to what is causing this and how I am supposed to solve this would be great.
You have an error in line 57:
def F(Y1,Y2,Y3):
return Y1*(omega_matter/(Y1**3) + (H**2)*(Y3**2)/(2.0*rho_c) + (v0*np.exp(-l*Y2*k))/(rho_c))**(1.0/2.0)
in expression H**2, where H is defined as a function in line 62:
def H(Y1,Y2,Y3):
...
I'm guessing you really meant to say: H(Y1,Y2,Y3)**2.
But that's not all. Line 52:
y1 == y1.append(y1[j] + (dh/6.0)*(k1 + 2.0*k2 + 2.0*k3 + k4))
No need to test for equivalence between y1 and None (that's what append() returns). I'm not sure what you tried to achieve here, maybe this?
y1.append(y1[-1] + (dh/6.0)*(k1 + 2.0*k2 + 2.0*k3 + k4))
Also, to access the last element of y1 (line 66), you can use a negative index:
Y1 = [y1[-1]] # instead of: Y1 = [y1[j]]
You have a variable named H and a function named H()
H = 2.27e-18
and
def H(Y1,Y2,Y3):
return -3*Y3*(H**2)*(omega_matter/(Y1**3) + (H**2)*(Y3**2)/(2.0*rho_c) + (v0*np.exp(-l*Y2*k))/(rho_c))**0.5 + (l*k*v0*np.exp(-l*Y2*k))/(H**2)
Change the name of the variable or the function for something else.
H_1 = 2.27e-18 #for example
As #randomir says, you probably want to look at his answer too
You can reproduce the error by simple doing:
H = 5
def H(a,b):
pass
print(H**3)
TypeError: unsupported operand type(s) for ** or pow(): 'function' and
'int'

Type error Python programming

I am trying to write some code for an assignment in python. What I am not finding anywhere is what is wrong and why it will not run. It is sense and move robotic localization function. I do not understand why this line will not work.
q.append(p[i] * (hit * sensor_right + (1 - hit) * (1-sensor_right)))
hit = a comparison between two strings. That evaluates to true or false which is 1 or 0, right?
sensor_right = 0.7
Traceback (most recent call last):
File "vm_main.py", line 26, in <module> import main
File "/tmp/sbdxfjuois/main.py", line 50, in <module> p = sense(p, measurements[k])
File "/tmp/sbdxfjuois/main.py", line 34, in sense q.append(p[i] * (hit * sensor_right + (1 - hit) * (1-sensor_right)))
TypeError: can't multiply sequence by non-int of type 'float'
Can you suggest anything for what I have here posted?
def sense(p, Z):
q = [ ]
for i in range(len(p)):
hit = (Z == colors[i])
q.append(p[i] * (hit * sensor_right + (1 - hit) * (1-sensor_right)))
s = sum(q)
for i in range(len(q)):
q[i] = q[i]/s
return q
As others have pointed out, this p variable is apparently a sequence of sequences. You can verify this by putting
print(type(p))
print(type(p[i]))
before the append statement. You'll probably see something like
tuple
tuple
If that's what you expected, then you'll need to loop over the other index of the array. Also, does your q need to be returned with the same shape? I suspect you want something more like this.
def sense(p, Z):
q = p[:]
for i in range(len(p)):
for j in range(len(p[i])):
hit = (Z == colors[i])
q[i][j] = (p[i][j] * (hit * sensor_right + (1 - hit) * (1-sensor_right)))
s = sum(q)
for i in range(len(q)):
q[i] = q[i]/s
return q
Note that you also might want to look into numpy arrays.
If you're correct about the other variables, it is telling you that p[i] is a sequence (most likely a list), which can't be multiplied by a float. Perhaps p[i] is not what you're expecting it to be?
Try printing p[i] before the line that throws an error.
The problem here is what others have said. You can only multiply a sequence by an int, not a float.
For example
>>> [1] * 3
[1, 1, 1]
>>> "f" * 6
ffffff
>>> [1] * 0.7
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't multiply sequence by non-int of type 'float'
Double check your data type for p, to make sure it is supposed to be a sequence. If that is truly what p should be, then make sure to convert the following to an int before multiplying
(hit * sensor_right + (1 - hit) * (1-sensor_right))
Related to what #Mike said, you could also do:
q = []
sum = 0
for i in p:
sub_q = []
for val in i:
computed_val = val * (hit * sensor_right + (1 - hit) * (1-sensor_right))
sum += computed_val
sub_q.append(computed_val)
q.append(sub_q)
I like that because it is more concise and doesn't have to build a bunch of ranges every time you call it, and it also reduces the number of times you iterate over the data, but to each their own.

Categories

Resources