import cmath
import math
import random
import time
P = []
V = []
Vin = []
def Compute_wn_win(n,V,Vin):
for i in range (0,n):
V.append(complex(math.cos(2*math.pi*i/n),math.sin(2*math.pi*i/n)))
Vin.append(1/(complex(math.cos(2*math.pi*i/n),math.sin(2*math.pi*i/n))))
Compute_wn_win(8,V,Vin)
for i in range(0,8):
random_number = random.uniform(-1.0,1.0)
P.append(random_number)
def FFT(P,V,n):
if(n==1):
return P[0]
else:
Peven = []
Podd = []
for i in range(0,n/2):
Peven.append(P[2*i])
Podd.append(P[(2*i)+1])
Vsquared = []
for i in range(0,n/2):
Vsquared.append(V[i]*V[i])
Sole = FFT(Peven,Vsquared,n/2)
Solo = FFT(Podd,Vsquared,n/2)
Sol = [0 for x in range(0,n)]
for i in range(0,n/2):
Sol[i] = Sole[i]+V[i]*Solo[i]
Sol[i+n/2] = Sole[i]-V[i]*Solo[i]
return Sol
Sol = FFT(P,V,8)
I am new to Python. I have the following code. However I get the following error for lines Sole = FFT(Peven,Vsquared,n/2) and Sol[i] = Sole[i]+V[i]*Solo[i]. However, I have defined, Sole, Solo and Sol as list data type so I don't understand why it mentions that float datatype does not have an attribute getitem
Exact Error is
Traceback (most recent call last):
File "/Users/globetrekker/Documents/CS5050/Assignment7/Test_py.py", line 40, in <module>
Sol = FFT(P,V,8)
File "/Users/globetrekker/Documents/CS5050/Assignment7/Test_py.py", line 33, in FFT
Sole = FFT(Peven,Vsquared,n//2)
File "/Users/globetrekker/Documents/CS5050/Assignment7/Test_py.py", line 33, in FFT
Sole = FFT(Peven,Vsquared,n//2)
File "/Users/globetrekker/Documents/CS5050/Assignment7/Test_py.py", line 37, in FFT
Sol[i] = Sole[i]+V[i]*Solo[i]
TypeError: 'float' object has no attribute '__getitem__'
Sole and Solo are the return values from recursive calls to FFT(), but FFT()'s base case (when n == 1) returns a float, not a list, so the step above the base case will fail by trying to index a float. Presumably, you want to change return P[0] in the base case to return [P[0]].
This is introducing a float:
for i in range(0,n/2):
Checkout: I keep getting this error for my simple python program: "TypeError: 'float' object cannot be interpreted as an integer"
Related
In response to this question, I took upon the challenge to make my understanding on R's density() function.
Since I'm pretty much very new to R, I have no ideas about vectors regarding the c() function, which made me use a list as the closest form.
I would make this function:
def density(x, bw, adjust):
bw2 = None
result = 0
if bw == "nrd0":
bw2 = 31.39367
else:
print("No such bandwidth.")
for i in range[len(x)]:
x[i] = x[i] * bw2
for i in range[len(x)]:
result = result + x[i]
return result * adjust
And I wanted to test it:
x = [1, 3, 5]
kern = density(x, "nrd0", 1)
print(kern)
And I gained 2 errors, the main one being a TypeError.
If you want to look into it further, here's the whole terminal message:
Traceback (most recent call last):
File "density.py", line 15, in <module>
kern = density(x, "nrd0", 1)
File "density.py", line 8, in density
for i in range[len(x)]:
TypeError: 'type' object is not subscriptable
How do I fix the TypeError?
for i in range[len(x)]:
x[i] = x[i] * bw2
You have range with [] while it should be (). Try to change it.
Below is an example:
l = [10, 20, 30, 40]
for i in range(len(l)):
print(l[i], end =" ")
print()
I'm currently encounter a TypeError: 'numpy.bool_' object is not iterable without knowing why. I've verified each variables that I used. Do you have any idea why this error occurs? Here a simplified code of mine that you can use to play with :
import numpy as np
def rad_to_deg(x):
deg = x*180/np.pi
return deg
def flag_PA(x,bornes_test):
index_0_test = int(np.where(bornes_test==0)[0][0])
for i in range(index_0_test):
cond1 = any(bornes_test[i] <= x < bornes_test[i+1])
cond2 = any(bornes_test[i]+180 <= x < bornes_test[i+1]+180)
if np.logical_or(cond1,cond2)==True :
flag_test=i
return flag_test
##################################### DATA READING ###########################
# Trouver les fichiers en Bande L et Bande N
bornes_PA = np.linspace(-180,180,18+1)
lambda_fichier = np.linspace(3E-6,11E-6)
u_coord_fichier = np.linspace(1,40)
v_coord_fichier = np.linspace(1,40)
baseline_fichier = np.sqrt(np.array(u_coord_fichier)**2+np.array(v_coord_fichier)**2).tolist()
for l in range(len(lambda_fichier)):
for b in range(len(baseline_fichier)):
deg = rad_to_deg(np.arctan2(u_coord_fichier[b],v_coord_fichier[b]))
result = int(flag_PA(deg,bornes_PA))
Here is the full error :
line 34, in <module>
result = int(flag_PA(deg,bornes_PA))
line 13, in flag_PA
cond1 = any(bornes_test[i] <= x < bornes_test[i+1])
The problem is that any tries to iterate over its argument.
The expression bornes_test[i] <= x < bornes_test[i+1] returns a scalar numpy.bool_, not an array.
Therefore any(bornes_test[i] <= x < bornes_test[i+1]) is trying to iterate over a scalar, as stated by the error message.
It looks like you can just delete the any and obtain the intended result.
I am trying to calculate a value of function f_integ, which is a result of integration of function f from 0 to x_v.
f = lambda x : x + 1
def f_integ(x_array):
int_result = np.zeros_like(x_array)
indexes = np.shape(x_array)[0]
for ind in range(indexes):
x_v = x_array[ind]
int_result[ind] = integ.quad(f, 0.0, x_v)[0]
return int_result
C = f_integ(1)
print "C", C
When I run this, I get the following error:
Traceback (most recent call last):
File "untitled.py", line 117, in <module>
C = f_integ(1)
File "scr1.py", line 110, in f_integ
indexes = np.shape(x_array)[0]
IndexError: tuple index out of range
I know that quad() returns a tuple, but I can not figure out how to put a number as an argument in the result of integration. I'm new to Python, please help.
Call the function like this:
C = f_integ(np.array([1]))
print "C", C
Currently you are passing a number to f_integ(), not an array. When it encounters np.shape(x_array)[0], the shape of a number is just (), so it cannot return anything at index 0 for an empty tuple.
In Python, I am trying to run a function in a class and get the following error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:/Users/X/Downloads/beamModel.py", line 58, in getTotalDeflection
beam.beamDeflection(loadsList, x)
TypeError: unbound method beamDeflection() must be called with beam instance as first argument (got list instance instead)
Code: beamModel.py:
class beam(object):
def __init__(self, E, I, L):
self.E = E
self.I = I
self.L = L
self.Loads = [(0.0, 0.0)] #[(Force, distance along beam)]
def beamDeflection(self, Load, x):
"""Calculates defeclection at point x due to single load"""
Force, distance = Load
L = self.L
E = self.E
I = self.I
b = L - distance
i = (Force*b)/(6*L*E*I)
j = ((L/b)*(x-distance)**3 - x**3 + (L**2 - b**2)*x)
k = (L**2 - x**2 - b**2)
if x > distance:
return i*j
else:
return i*k
def getTotalDeflection(self, x):
"""Calculate total deflection of beam due to multiple loads"""
loadsList = self.Loads
beam.beamDeflection(loadsList, x)
Now I need to run a list of tuples through the function beamDeflection (which is working) and sum the results to give me the value of the total deflection, which should be returned by the function getTotalDeflection.
EDIT:
I changed the getTotalDeflection function to:
def getTotalDeflection(self, x):
"""Calculate total deflection of beam due to multiple loads
"""
loadsList = self.Loads
self.beamDeflection(loadsList, x)
which is now giving me the error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:/Users/X/Downloads/beamModel.py", line 58, in getTotalDeflection
self.beamDeflection(loadsList, x)
File "C:/Users/X/Downloads/beamModel.py", line 39, in beamDeflection
Force, distance = Load
ValueError: need more than one value to unpack
The problem could be because you are calling beamDeflection() not on an instance of beam but on the static beam class itself.
Assuming that is the problem, you could probably rewrite your getTotalDeflection method like so:
def getTotalDeflection(self, x):
"""Calculate total deflection of beam due to multiple loads"""
loadsList = self.Loads
self.beamDeflection(loadsList, x)
this is my code for the k nearest neighbor algorithm:
import numpy as np
from EuclideanDistance import EuclideanDistance
dataset = np.loadtxt('C:\Users\Toshiba\Documents\machine learning\RealEstate.csv', delimiter=',', usecols=(2,3,4,5))
p1 = ()
def normalizeToZscores(data):
'''Normalizes the variables to z-scores'''
zScores = list()
for s in data:
zScore = (s - np.mean(data))/np.std(data)
zScores.append(zScore)
return np.asarray(zScores)
def InOutBudget(data):
'''Decides whether a particular house is within
or outside the budget of $153000 and assigns values of 1 and 0 respectively'''
data2 = list()
for i in data:
if (i > 153000): data2.append(0)
else: data2.append(1)
return np.array(data2)
classes = dataset[:,0]
classes = classes.reshape((dataset.shape[0],1))
classes = InOutBudget(classes)
data = dataset[:20,:]
data = normalizeToZscores(data)
p1s = dataset[20:400,:]
def measureDis(data, p1):
listD = []
for x in data:
D = EuclideanDistance(x, p1)
listD.append(D)
return listD
def most_common(lst):
'''Finds the most frequently occuring element of a list.
It will be used to predict a class based on the classification
of the k-nearest neighbours'''
return max(set(lst), key=lst.count)
def findKnn(k):
'''K nearest neighbours algorithm'''
knns = list()
errors = list()
#for i in k:
for p1 in p1s:
# Create a list of tuples containing distance and class,
# Then sort them by shortest distance
tuples = zip(measureDis(data,p1), classes[20:400])
tuples = sorted(tuples)
knn = tuples[:k]
print knn
knn = [x[1] for x in knn]
knn = most_common(knn)
knns = knns.append(knn)
print knn
error = np.abs(knn - p1)
errors = errors.append(error)
errorsNum = np.sum(errors)
return knns
But I keep getting:
Traceback (most recent call last):
File "C:\Users\Toshiba\workspace\assignment5\src\knn2.py", line 76, in <module> knn = findKnn(k)
File "C:\Users\Toshiba\workspace\assignment5\src\knn2.py", line 64, in findKnn knns = knns.append(knn)
AttributeError: 'NoneType' object has no attribute 'append'
I know the code is really amateur, but could someone please help me just solve the issue?
list.append doesn't return the list. Simply do:
knns.append(knn)
instead of:
knns = knns.append(knn)
append does not return the list, it returns None, so you are clobbering it after the first loop.