Python 3 recognized an element as a string - python

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'

Related

Why do I get an 'int' object is not iterable ERROR in pyhton statistics?

So I'm working on a school exercise with python jupyter and I'm supposed to write a function that calculates the regression_coefficients out of two lists of integers or floatingpoints(Iguess) (list are arguments x and y). So i wrote the code and when I run it i get a TypeError: 'int' object is not iterable. And I know there are a lot of topics about this particular error but I can't find a solution for myself, becauss x and y only contain lists of integers so i don't get why its not iterable. Can someone please help me, I have a deadline tomorrow :( .
Ps: Here's my code -->
def regression_coefficients(x,y):
""" This function calculates the regression offset(a) and the slope(b)
X and Y are both list of integers or floatingpoints
"""
Xi_keer_Yi = []
Xi_kwadraat = [nummer ** 2 for nummer in x]
for x, y in zip(x, y):
Xi_keer_Yi.append(x * y)
Xi_keer_Yi_som = sum(Xi_keer_Yi)
Xi_kwadraat_som = sum(Xi_kwadraat)
X_som = sum(x)
Y_som = sum(y)
if x < y:
n = len(x)
elif y < x:
n = len(y)
else:
n = len(x)
b_boven = n * Xi_keer_Yi_som - X_som * Y_som
b_onder = n * Xi_kwadraat_som - (X_som)**2
b = b_boven / b_onder
a = y[0] - (b * x[0])
return a,b
print(regression_coefficients([1,2,3],[2,1,3]))
#test functie
#Test.test_regressie.test(regression_coefficients)
This is the error -->
<ipython-input-17-b8ba668746c1> in <module>
35
36
---> 37 print(regression_coefficients([1,2,3],[2,1,3]))
38 # test functie
39 #Test.test_regressie.test(regression_coefficients)
<ipython-input-17-b8ba668746c1> in regression_coefficients(x, y)
13 Xi_keer_Yi_som = sum(Xi_keer_Yi)
14 Xi_kwadraat_som = sum(Xi_kwadraat)
---> 15 X_som = sum(x)
16 Y_som = sum(y)
17
TypeError: 'int' object is not iterable

Unsupported operand types 'NoneType'

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)))

Im currently writing a gravity simulation and I am getting a type Error in my code

The Problem occurs in line 29:
It is a Type Error
I can't figure out where I went wrong with my parameters. It should assign every a[i][k] with a value but it just ends up with the following error message:
a[i][k].append(g * m[i] * dr[k]/d3)
TypeError: 'int' object is not subscriptable
Here the full code:
import numpy as np
from numpy import absolute
from numpy import power
r = [[1,1,1],[1,1,1],[0,0,0]]
v = [[0,0,0],[0,0,0],[0,0,0]]
a = [[0,0,0],[0,0,0],[0,0,0]]
m = [1,1,1]
O = -1
N = 3
def beschleunigung(O, N, m, r, a):
i = 0
k = 0
dr = [0,0,0]
d3 = 0
g = 1
for k in range(1,3):
a[i][k] = 0
for i in range(1,N):
if i != O:
for k in range(1,3):
a = (r[i][k])
b = (r[0][k])
dr[k] = a - b
d3 = np.power(np.absolute(dr),3)
for k in range(1,3):
a[i][k].append(g * m[i] * dr[k]/d3)
beschleunigung(O,N,m,r,a)
print(a[1])
When your code executes the line a = (r[i][k]), a becomes an integer, rather than a list of lists as it was in the input to this function. This causes your append to fail as you cannot append to an integer.
I expect that you intended to create another variable to use in your subtraction with b - make sure to use a name that is not already defined in your scope.

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'

What is the reason for TypeError: 'Zero' object has no attribute '__getitem__'?

I have written the following code in python 2.7 in order to calculate an integration numerically and then use the result of this integration for further steps of the project.
import numpy as np
from scipy import linspace,logspace
from cosmicpy import *
Omega_Matter, Omega_DarkEnergy, A, b, rho_critical, m = 0.306, 0.694, 0.3222, 0.707, 2.77536627e+11, 1000000
def D(z):
a = 1/(1+z)
x = (Omega_DarkEnergy/Omega_Matter)**(1/3)*a
return (5/2)*(Omega_Matter/Omega_DarkEnergy)**(1/3)*x**(-3/2)*(1+x**3)**(1/2)* \
(x**2/(3*x**3 + 3) - np.log(x + 1)/9 + np.log(x**2 - x + 1)/18 \
+ np.sqrt(3)*np.arctan(2*np.sqrt(3)*x/3 \
- np.sqrt(3)/3)/9 + np.sqrt(3)*np.pi/54)
def delta(z):
return D(z)/D(0)
def W(k, M):
rho_m = rho_critical*Omega_Matter
R = (3*M/(4*np.pi*rho_m))**(1/3)
x = k*R
return (3/x)*(sin(x)-x*cos(x))
my_cosmology = cosmology(Omega_m=0.306, Omega_de=0.694, h=0.679, Omega_b=0.0483, n=0.968, tau=0.067, sigma8=0.815, w=-1)
k_array = np.logspace(-16,4,m)
P = my_cosmology.pk_lin(k_array)
def sigma_squared(z, M):
dk = (np.max(k_array)-np.min(k_array))/(m-1)
summation = []
for k in k_array:
Integral = 0
Integrand = k**2*P[k]*(W(k, M))**2
Integral += dk * np.sum(Integrand[k])
summation.append(Integral)
return ((delta(z))**2/(2*(np.pi)**2))*summation[-1]
print(summation)
sigma_squared(0.01, 1e+9)
As I write more of the code, I check my steps one by one by getting a print and see if the output is what I expect. However, I am unable to produce the final product of the last function which is supposed to be a value given the values for the variables z and M. In particular I am sure that something is wrong with the integration inside that function because I am not getting any thing for print(summation) which is supposed to be a big 1d array whose last element print(summation[-1])should give me the area under the curve (upto a pre-factor defined in the final return of the function). Here is the error message and I couldn't find any on-line source for the particular error message I am getting. Your help is greatly appreciated.
mycode.py:95: VisibleDeprecationWarning: using a non-integer number
instead of an integer will result in an error in the future
Integrand = k**2*P[k]*(W(k, M))**2 Traceback (most recent call last):
File "mycode.py", line 102, in
sigma_squared(0.01, 1e+9) File "mycode.py", line 96, in sigma_squared
Integral += dk * np.sum(Integrand[k]) TypeError: 'Zero' object has no attribute 'getitem'
Edited Code (which is too slow to know if it is working correctly):
k_array = np.logspace(-16,4,m)
my_cosmology = cosmology(Omega_m=0.306, Omega_de=0.694, h=0.679, Omega_b=0.0483, n=0.968, tau=0.067, sigma8=0.815, w=-1)
P = my_cosmology.pk_lin(k_array)
M_array = np.logspace(8,16,n)
def W(k, M):
rho_m = rho_critical*Omega_Matter
R = (3*M/(4*np.pi*rho_m))**(1/3)
y = k*R
return (3/y**3)*(sin(y)-y*cos(y))
def sigma_squared(z, M):
dk = (np.max(k_array)-np.min(k_array))/(m-1)
summation = []
for k in k_array:
for M in M_array:
Integral = 0
Integrand = k**2*P[k]*(W(k, M))**2
Integral += dk * np.sum(Integrand)
summation.append(Integral)
return ((delta(z))**2/(2*(np.pi)**2))*summation[-1]
print(sigma_squared(0, 1e+9))

Categories

Resources