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.
Related
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)))
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.
I wrote the following code, after printing about 10 outputs it gets error
return 1/sqrt(Om*(1+z)**3+omg0*(1+z)**6+(1-Om-omg0))
ValueError: math domain error
the three first functions are correct and work well in other programs please do not be sensitive about their structures, I think the problem is in for-loop and choosing some values which cannot satisfy the condition of sqrt. Could I add some lines to tell Python avoid numbers which lead to math domain error? If yes, How should I do that? I mean passing the step which leads to negative value under sqrt?
Cov is a 31*31 mtrix, xx[n] is a list of 31 numbers.
def ant(z,Om,w):
return 1/sqrt(Om*(1+z)**3+w*(1+z)**6+(1-Om-w))
def dl(n,Om,w,M):
q=quad(ant,0,xx[n],args=(Om,w))[0]
h=5*log10((1+xx[n])*q)
fn=(yy[n]-M-h)
return fn
def c(Om,w,M):
f_list = []
for i in range(31): # the value '2' reflects matrix size
f_list.append(dl(i,Om,w,M))
A=[f_list]
B=[[f] for f in f_list]
C=np.dot(A,Cov)
D=np.dot(C,B)
F=np.linalg.det(D)*0.000001
return F
N=100
for i in range (1,N):
R3=np.random.uniform(0,1)
Omn[i]=Omo[i-1]+0.05*np.random.normal()
wn[i]=wo[i-1]+0.05*np.random.normal()
Mn[i]=Mo[i-1]+0.1*np.random.normal()
L=exp(-0.5*(c(Omn[i],wn[i],Mn[i])-c(Omo[i-1],wo[i-1],Mo[i-1])))
if L>R3:
wo[i]=wn[i]
else:
wo[i]=wo[i-1]
print(wo[i])
The output is:
0.12059556415714912
0.16292726528216397
0.16644447885609648
0.1067588804671105
0.0321446951572128
0.0321446951572128
0.013169965429457382
Traceback (most recent call last):
......
return 1/sqrt(Om*(1+z)**3+omg0*(1+z)**6+(1-Om-omg0))
ValueError: math domain error
Here are some options:
Replace sqrt(...) with (...)**0.5. This will produce complex numbers, which may or may not be acceptable. For example (-1)**0.5 produces i which in Python will appear as 1j (ignoring floating point errors).
Catch errors and move on. Since you probably want to catch the errors higher up, I recommend translating the ValueError from sqrt into a custom error:
class SqrtError(ValueError):
pass
def ant(z, Om, w):
val = Om * (1 + z) ** 3 + w * (1 + z) ** 6 + (1 - Om - w)
try:
sq = sqrt(val)
except ValueError:
raise SqrtError
return 1 / sq
Then it sounds like you want to keep trying new random numbers until you get one that works, which could be done like so:
for i in range(1, N):
R3 = np.random.uniform(0, 1)
while True:
Omn[i] = Omo[i - 1] + 0.05 * np.random.normal()
wn[i] = wo[i - 1] + 0.05 * np.random.normal()
Mn[i] = Mo[i - 1] + 0.1 * np.random.normal()
try:
L = exp(-0.5 * (c(Omn[i], wn[i], Mn[i]) - c(Omo[i - 1], wo[i - 1], Mo[i - 1])))
except SqrtError:
continue
else:
break
if L > R3:
wo[i] = wn[i]
else:
wo[i] = wo[i - 1]
Your code is trying to find the square root of a negative number.
This is not allowed with real-valued numbers (for obvious mathematical reasons), so your best bet is to use a try/except block:
def ant(z,Om,w):
try:
return 1/sqrt(Om*(1+z)**3+omg0*(1+z)**6+(1-Om-omg0))
except ValueError:
return None
Using python 2.7 I am trying to compute the following rather difficult set of equations.
I have successfully implemented the first two, but am struggling with the third. Here is my attempt,
def pi_tau( r ):
return (1 - (1 - r)**(t + 1))/(2 - r)
def mean_field( r ):
return 1 - (1 - r)**t
def pi_neighbour( r ):
inside = []
for kappa_dash in range(0, kappa - 1):
Binomial_Coefficient = (math.factorial(kappa - 1)) / (math.factorial(kappa - 1 - kappa_dash)*math.factorial(kappa_dash))
top = ((mean_field( r )*pi_tau( r ))**kappa_dash)*(1 - mean_field( r )*pi_tau( r ))**(kappa - 1 - kappa_dash)
bottom = kappa_dash + 1
fraction = top/bottom
inside.append(kappa_dash)
inside[kappa_dash] = inside[kappa_dash] + fraction*Binomial_Coefficient
return pi_tau*inside
I then try to call this function
# set parameters
r = 0.15
kappa = 2.1
T = 10
ppp_t = []
mmm_f = []
nnn_t = []
for t in range(0, T):
ppp_t.append(pi_tau( r ))
mmm_f.append(mean_field( r ))
nnn_t.append(pi_neighbour( r ))
I get the following error message
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-41-9bcf462306f0> in <module>()
6 ppp_t.append(pi_tau( r ))
7 mmm_f.append(mean_field( r ))
----> 8 nnn_t.append(pi_neighbour( r ))
<ipython-input-39-d9acdd7490f9> in pi_neighbour(r)
19 inside[kappa_dash] = inside[kappa_dash] + fraction*Binomial_Coefficient
20
---> 21 return pi_tau*inside
TypeError: can't multiply sequence by non-int of type 'function'
I am looking for any advice on how to implement the third function and improve on my method.
There are several weird things here:
you calculate the top, bottom, and bionomial all in the for loop, but don't sum up in that for loop; and
you multiply the pi_tau function with a list?
return pi_tau*inside
you use range(0, kappa - 1), but the upperbound of range(..) is exclusive
Nevertheless, you make things quite hard. You could use the following approach:
from math import factorial
def pi_neighbour(r):
sum = 0.0
for kappa_dash in range(0,kappa):
bin_coeff = factorial(kappa-1)/(factorial(kappa-1-kappa_dash)*factorial(kappa_dash))
top = ((mean_field(r)*pi_tau(r))**kappa_dash)*(1-mean_field(r)*pi_tau(r))**(kappa-1-kappa_dash)
sum += bin_coeff*top/(kappa_dask+1)
return pi_tau(r)*sum
What I believe you meant to do is the following in line 21 of the traceback:
return pi_tau(r)*inside
You forgot to call the function, and so it is attempting to multiply an integer by a function, rather than the return value of the function.
The error is that you are multiplying a list, that is inside and a integer, that is return of pi_tau(r)
Do this instead (a list comprehension)
try this:
return [i*pi_tau(r) for i in inside]
I am having a problem with calling a function twice. If I comment my last 3 lines and keep show(), I don't get any errors and things come as they are suppose to. However, if I don't comment them out calling the last function again gives me this error:
Traceback (most recent call last):
File "second_1.py", line 29, in <module>
domega=c_d(len(t),t,z)
File "second_1.py", line 25, in c_d
dy[1:-1]=(y[2:]-y[0:-2])/(x[2:]-x[0:-2])
TypeError: unsupported operand type(s) for -: 'list' and 'list'
Here is the function:
import numpy as np
from pylab import *
import time
t_initial=time.time()
clf()
t,hp,hn= np.loadtxt("Richardson.dat", usecols=(0,1,2),comments='#', unpack=True) # to select just a few columns
print(time.time()-t_initial)
def phi(y,x):
return(np.arctan(y/x))
phase=[0.0]*len(t)
phase=phi(hp[0:],hn[0:])
#plot(t,phase)
#show()
def c_d(order,x,y):
dy=[0.0]*order
dy[0]=(y[1]-y[0])/(x[1]-x[0])
dy[-1]=(y[-1]-y[-2])/(x[-1]-x[-2])
dy[1:-1]=(y[2:]-y[0:-2])/(x[2:]-x[0:-2])
return(dy);
z=c_d(len(t),t,phase);
plot(t,z)
print(len(z)-len(t))
domega=c_d(len(t),t,z)
plot(t,domega)
show()
The problem is very clearly explained in the error message:
The '-' operand is not applicable for the type list.
(y[2:]-y[0:-2])/(x[2:]-x[0:-2])
y[2:] slices a list and returns a list. y[0:-2] slices also a list and returns a list. So there you have 2 lists.
y[2:] (a list) -(your operator) y[0:-2] (a list)
And list - list is not defined (there is no syntax for: 'listObject' - 'listObject').
BUT: the + operator is defined for lists (example):
l = ["ja"]
m = ["nein"]
n = l + m
print n
# output: ['ja', 'nein']
Take a look here for these different kind of possible operators:
https://docs.python.org/2/library/stdtypes.html
As explained in the other answers, you can not subtract regular Python lists. So why does it work the first time, and fails the second? Let's take a look at the code.
t, hp, hn = np.loadtxt(...)
...
def c_d(order, x, y):
dy = [0.0] * order
dy[ 0] = (y[1] -y[0]) / (x[ 1]-x[0])
dy[-1] = (y[-1]-y[-2]) / (x[-1]-x[-2])
dy[1:-1] = (y[2:]-y[0:-2]) / (x[2:]-x[0:-2])
return dy
z = c_d(len(t), t, phase)
...
domega = c_d(len(t), t, z)
...
When you first call c_d, the parameters x and y seem to be numpy arrays (at least t and phase are results of numpy function calls), and for those, - is a legal operation. But inside c_d, you create and finally return a regular Python list, dy, so when you then call c_d again with the result of the first call as y, this part y[2:]-y[0:-2] will fail, as y now is a regular list.
Make sure your dy is a numpy array, too, i.e. dy = np.array([0.0] *order) or just dy = np.zeros(order), then it should work.
As stated by Cyber and ProgrammingIsAwsome the error is on line
(y[2:]-y[0:-2])/(x[2:]-x[0:-2])
where you actually try to substract lists.
You could write explicitely :
for i in range(1, order - 1):
dy[i]=(y[i+1]-y[i-1])/(x[i+1]-x[1-1])