__init__() missing 1 required positional argument , but i think i put it? - python

I program an educational game where the user has to reproduce a piece of factory offered by the computer. When I instantiate objects in the Piece class in my Application class and use the drawPiece () method, I have this error:
Traceback (most recent call last):
File "/Users/boriselgareh/Downloads/DMV2 5/Application.py", line 32, in <module>
Application(8).mainloop()
File "/Users/boriselgareh/Downloads/DMV2 5/Application.py", line 12, in __init__
self.initPieces()
File "/Users/boriselgareh/Downloads/DMV2 5/Application.py", line 21, in initPieces
pieceModele=PieceModele(Canvas())
File "/Users/boriselgareh/Downloads/DMV2 5/Piece.py", line 82, in __init__
Piece.__init__(self)
TypeError: __init__() missing 1 required positional argument: 'can'
Here are the two classes that interest us,
The Piece and Application classes are contained in separate files :
from VueChaine import *
from Chaine import *
from tkinter import *
from Piece import *
class Application(Tk):
def __init__(self,nbCotes):
Tk.__init__(self)
self.nbCotes=nbCotes
self.initFenetre()
self.initPieces()
def initFenetre(self):
self.title("l'usine TTT")
self.chaine=Chaine((3*self.nbCotes-2)//2)
self.afficheChaine=VueChaine(self,self.nbCotes)
self.afficheChaine.grid()
def initPieces(self):
pieceModele=PieceModele(Canvas(self))
pieceUsine=PieceUsine(Canvas(self))
pieceModele.getCan().pack(self)
pieceUsine.getCan().pack(self)
pieceUsine.dessinerPieces()
pieceModele.dessinerPieces()
if __name__=="__main__":
Application(8).mainloop()
from random import *
from math import *
from tkinter import *
class Piece(object):
def __init__(self,can,x=100,y=100,r=100,nbCotes=8):
self.__nbCotes=nbCotes
self.__can=can
self.xCentre=x
self.yCentre=y
self.rayon=r
self.generer()
def dessinerPieces(self):
sommets=[]
for i in range(self.getNbCotes()):
sommets.append([self.xCentre+self.rayon * cos(2 * pi * (i+1/2) / self.getNbCotes()),
self.yCentre +self.rayon * sin(2 * pi * (i+1/2) / self.getNbCotes())])
self.getCan().create_polygon(sommets, outline='gray', fill='gray')
self.getCan().pack()
delta=self.rayon-self.rayon*cos(pi/self.getNbCotes())
angle = (2 * pi) / self.getNbCotes()
for i in range(self.getNbCotes()//2):
if self.traits[i] != 0:
x0 = self.xCentre + (self.rayon - delta) * cos(angle * i)
x1 = self.xCentre + (self.rayon - delta) * cos(angle * i + pi)
y0 = self.yCentre + (self.rayon - delta) * sin(angle * i)
y1 = self.yCentre + (self.rayon - delta) * sin(angle * i + pi)
self.getCan().create_line(x0, y0, x1, y1, width=self.traits[i]**2, fill='lightgrey')
if self.trous[i] == 2 or self.trous[i] == 3:
x0 = self.xCentre + (self.rayon - delta) / 1.25 * cos(angle * i) - 7
y0 = self.yCentre + (self.rayon - delta) / 1.25 * sin(angle * i) - 7
x1 = self.xCentre + (self.rayon - delta) / 1.25 * cos(angle * i) + 7
y1 = self.yCentre + (self.rayon - delta) / 1.25 * sin(angle * i) + 7
x2 = self.xCentre + (self.rayon - delta) / 1.25 * cos(angle * i + pi) - 7
y2 = self.yCentre + (self.rayon - delta) / 1.25 * sin(angle * i + pi) - 7
x3 = self.xCentre + (self.rayon - delta) / 1.25 * cos(angle * i + pi) + 7
y3 = self.yCentre + (self.rayon - delta) / 1.25 * sin(angle * i + pi) + 7
self.getCan().create_oval(x0, y0, x1, y1, fill='yellow')
self.getCan().create_oval(x2, y2, x3, y3, fill='yellow')
if 1 or 3 in self.traits :
x = self.xCentre
y = self.yCentre
self.getCan().create_oval(x - 7, y - 7, x + 7, y + 7, fill='yellow')
#mainloop()
def generer(self):
raise NotImplementedError('...')
def getNbCotes(self):
return self.__nbCotes
def setNbCotes(self,nbCotes):
self.__nbCotes=nbCotes
def getCan(self):
return self.__can
def __eq__(self, other):
nouveau_trous = self.trous
res=()
for i in range(len(nouveau_trous)):
if nouveau_trous[i] == 3 or nouveau_trous[i]==1:
nouveau_trous[i]=nouveau_trous[i]-1
retenue=1
res=(nouveau_trous,self.traits,retenue)
return res==other
class PieceModele(Piece):
def __init__(self,trous=[],traits=[]):
self.trous=trous
self.traits=traits
Piece.__init__(self)
def generer(self):
self.trous=[randint(0,3) for i in range(self.getNbCotes()//2)]
self.traits=[randint(0,3) for i in range(self.getNbCotes()//2)]
def __repr__(self):
return str(self.trous)+str(self.traits)+" "+str(self.getNbCotes())
class PieceUsine(Piece):
def __init__(self,trous=[],traits=[]):
self.trous=trous
self.traits=traits
Piece.__init__(self)
def generer(self):
self.trous=[ 0 for i in range(self.getNbCotes()//2)]
self.traits=[ 0 for i in range(self.getNbCotes()//2)]
def trouer(self,nb):
self.trous[0]=nb
def tracer(self,epaisseur):
self.traits[0]=epaisseur
def tourner(self,angle):
for i in range(angle):
self.trous.insert(0,self.trous.pop())
self.traits.insert(0,self.traits.pop())
def __repr__(self):
return str(self.trous) + str(self.traits) + " " + str(self.getNbCotes())
if __name__=="__main__":
p1=PieceModele()
p2=PieceUsine()
print(p1)
p1.dessinerPieces()
print(p1)

Piece class takes 1 positional argument namely can.
class Piece(object):
def __init__(self,can,x=100,y=100,r=100,nbCotes=8):
.....
PieceModel class extends piece and is trying to do a super initialize without passing value for can (see last line in this block of code)
class PieceModele(Piece):
def __init__(self,trous=[],traits=[]):
self.trous=trous
self.traits=traits
Piece.__init__(self)

Related

how to speed up master.scene._render_pygame_def_update() time

im trying to make a 3d renderer but i can only get at most 20fps on idle.
i tried using #functools.lru_cache(maxsize=None) on project_and_rotate() and got it up to 40fps on idle.
is there any way i could make this any faster
im using a long math formula i found a few month ago but it seems to be to slow for the map in projected_des
from math import *
import pygame
import numpy
from functools import lru_cache
#lru_cache(maxsize=None)
def project_and_rotate(x, y, z,rotx,roty,rotz,posx,posy,posz,cx,cy,cz,scale,render_distance):
x,y,z=x-posx,y-posy,z-posz
if abs(x)>render_distance or abs(z)>render_distance:return None
px = (((x * cos(rotz) - sin(rotz) * y) * cos(roty) - z * sin(roty)) * (315 / ((((z * cos(roty) + (x * cos(rotz) - sin(rotz) * y) * sin(roty)) * cos(rotx) + (y * cos(rotz) + x * sin(rotz)) * sin(rotx)) + 5) + cz))) * scale + cx
py = (((y * cos(rotz) + x * sin(rotz)) * cos(rotx) - (z * cos(roty) + (x * cos(rotz) - sin(rotz) * y) * sin(roty)) * sin(rotx)) * (315 / ((((z * cos(roty) + (x * cos(rotz) - sin(rotz) * y) * sin(roty)) * cos(rotx) + (y * cos(rotz) + x * sin(rotz)) * sin(rotx)) + 5) + cz))) * scale + cy
return [round(px),round(py)]
class coordinate:
def __init__(self,x,y,z):
self.x=x
self.y=y
self.z=z
class verticies_structure:
def __init__(self):
self._verts=[]
def add_vert(self,x,y,z):
self._verts.append(coordinate(x,y,z))
def get_coords(self,indexes):
return self._verts[indexes[0]:indexes[1]]
class camera:
def __init__(self,w,h,render_distance,fov=45):
self.fov=360-fov
self.w=w
self.h=h
self.x=0
self.rx=0
self.cx=0
self.y=0
self.ry=0
self.cy=0
self.z=0
self.rz=0
self.cz=0
self.render_distance=render_distance
def false(f,value):
if value==f:
value=f+0.01
return value
def inf360(value):
if value>359:value=0
if value<0:value=359
return value
class mesh(object):
def __init__(self,file_obj,cam):
self.cam=cam
self.verts=verticies_structure()
self.source=file_obj
self.read_object_file()
self.verts=verticies_structure()
size=100
for x in range(size):
for z in range(size):
self.verts.add_vert(x-size//2,0,z-size//2)
self.w2s_vect=numpy.vectorize(self.w2s)
self.array_verts=numpy.array(self.verts._verts)
def w2s(self,coord):
cam=self.cam
return project_and_rotate(coord.x,coord.y,coord.z,cam.ry,cam.rx,cam.rz,cam.x,cam.y,cam.z,cam.cx,cam.cy,cam.cz,10,cam.render_distance)
def projected_des(self,cam):
#return self.w2s_vect(self.array_verts).tolist()
return map( lambda coord:project_and_rotate(coord.x,coord.y,coord.z,cam.ry,cam.rx,cam.rz,cam.x,cam.y,cam.z,cam.cx,cam.cy,cam.cz,10,cam.render_distance),self.verts.get_coords([0,-1]))
def read_object_file(self):
self.verts=verticies_structure()
import re
reComp = re.compile("(?<=^)(v |vn |vt |f )(.*)(?=$)", re.MULTILINE)
with open(self.source) as f:
data = [txt.group() for txt in reComp.finditer(f.read())]
v_arr, vn_arr, vt_arr, f_arr = [], [], [], []
for line in data:
tokens = line.split(' ')
if tokens[0] == 'v':
v_arr.append([float(c) for c in tokens[1:]])
elif tokens[0] == 'vn':
vn_arr.append([float(c) for c in tokens[1:]])
elif tokens[0] == 'vt':
vn_arr.append([float(c) for c in tokens[1:]])
elif tokens[0] == 'f':
f_arr.append([[int(i) if len(i) else 0 for i in c.split('/')] for c in tokens[1:]])
vertices, normals = [], []
for face in f_arr:
for tp in face:
self.verts.add_vert(*v_arr[tp[0]-1])
self.array_verts=numpy.array(self.verts._verts)
class draw:
class frame:
class pygame_uitl:
def grid(rowx,rowy,px,color=(255,255,255)):
display=pygame.display.get_surface()
for r in range(rowx):
r+=1
pygame.draw.line(display,color,(0,(display.get_height()/(rowx+1))*r),(display.get_width(),(display.get_height()/(rowx+1))*r),px)
for r in range(rowy):
r+=1
pygame.draw.line(display,color,((display.get_width()/(rowy+1))*r,0),((display.get_width()/(rowy+1))*r,display.get_height()),px)
class system:
class pygame_util:
def get_orientation():
inf=pygame.display.Info()
w,h=inf.current_w,inf.current_h
if w>h:
return 1
else:
return 0
class Drivers:
class Pygame:
DEFAULT="PG-default"
SDL2="PG-sdl2"
class master:
class scene:
def __init__(self,wh:list,display_driver:str,render_distance:int,fps:int):
self._model={
"class 1":[],
"class 2":[],
"class 3":[],
"class 4":[]}
self._fps=fps
self._window_wh=wh
self._driver=display_driver
self._camera=camera(*wh,render_distance)
self._mode="mesh"
self._super_ls=0
if display_driver==Drivers.Pygame.DEFAULT:
self._render_pygame_def_setup()
def add_model(self,file):
model=mesh(file,self._camera)
vertexes=len(model.verts._verts)
if vertexes>100:
self._model["class 4"].append(model)
elif vertexes>50:
self._model["class 3"].append(model)
elif vertexes>25:
self._model["class 2"].append(model)
else:
self._model["class 1"].append(model)
def regulate_camera(self):
self._camera.rx,self._camera.ry,self._camera.rz=false(0,self._camera.rx),false(0,self._camera.ry),false(0,self._camera.rz)
self._camera.cx,self._camera.cy,self._camera.cz=false(0,self._camera.cx),false(0,self._camera.cy),false(0,self._camera.cz)
def correct_camera(self,orient=1):
self._orient=orient
if orient:
self._camera.cx=self._window_wh[1]//2
self._camera.cy=self._window_wh[0]
self._camera.ry=0.4
else:
self._camera.cx=self._window_wh[0]//2
self._camera.cy=self._window_wh[1]
self._camera.ry=0.2
def auto_render_distance(self):
if self._driver==Drivers.Pygame.DEFAULT:
if self._pygame_clock.get_fps()+5>self._fps:
self._camera.render_distance+=1
else:
self._camera.render_distance-=1
def landscape_super(self):
self._super_ls=1
self._lss_hdri_file_jpg_surf=pygame.Surface([self._window_wh[0],self._window_wh[1]//2.01])
self._lss_hdri_file_jpg_surf.fill((200,220,255))
def _render_pygame_def_setup(self):
self._pygame_clock=pygame.time.Clock()
self._pygame_screen=pygame.display.set_mode((self._camera.w,self._camera.h),pygame.DOUBLEBUF|pygame.HWACCEL|pygame.HWSURFACE)
def _render_pygame_def_update(self):
self._pygame_screen.fill((0,70,0))
self.regulate_camera()
for idx,vclass in self._model.items():
for model in vclass:
for point in model.projected_des(self._camera):
if point!=None:
try:self._pygame_screen.set_at(point,(255,255,255))
except:pass
if self._super_ls:
self._pygame_screen.blit(self._lss_hdri_file_jpg_surf,(0,0))
def _render_pygame_def_finish(self):
pygame.display.flip()
self._pygame_clock.tick(self._fps)
scene=master.scene([2176,1080],Drivers.Pygame.DEFAULT,render_distance=25,fps=60)
scene.add_model("cube.obj")
scene.correct_camera(0)
scene.landscape_super()
#make the sky mapped to edge of render
pygame.font.init()
while 1:
rx,ry=pygame.mouse.get_rel()
scene._camera.rx+=rx/200
scene._render_pygame_def_update()
#scene.auto_render_distance()
scene._pygame_screen.blit(pygame.font.SysFont(None,60).render(str(scene._pygame_clock.get_fps()),None,(255,0,0)),(0,0))
scene._render_pygame_def_finish()
Something like this would reduce the number of math expressions in project_and_rotate
#lru_cache(maxsize=None)
def project_and_rotate(x, y, z,rotx,roty,rotz,posx,posy,posz,cx,cy,cz,scale,render_distance):
x,y,z=x-posx,y-posy,z-posz
if abs(x)>render_distance or abs(z)>render_distance:
return None
cos_rotz = cos(rotz)
sin_rotz = sin(rotz)
cos_roty = cos(roty)
sin_roty = sin(roty)
cos_rotx = cos(rotx)
sin_rotx = sin(rotx)
intermediate_1 = (x * cos_rotz - sin_rotz * y)
intermediate_2 = (z * cos_roty + intermediate_1 * sin_roty)
intermediate_3 = (y * cos_rotz + x * sin_rotz) * sin_rotx)
intermediate_4 = (315 / (((intermediate_2 * cos_rotx + intermediate_3 + 5) + cz))) * scale
px = ((intermediate_1 * cos_roty - z * sin_roty) * intermediate_4 + cx
py = (((y * cos_rotz + x * sin_rotz) * cos_rotx - intermediate_2 * sin_rotx) * intermediate_4 + cy
return [round(px), round(py)]
However, to fully improve your script -- it would be wise to profile the code to see where the script is taking the most time.
For a better discussion you should see https://codereview.stackexchange.com/

IndexError: list assignment index out of range.. Can't find mistake in the code

guys. I can't find mistake in code.. Help me please)
x = [2]
y = [2]
z = [2]
x[0] = int(random.randint(xmin, int((2 * xmax - xmin) / 2)))
y[0] = int(random.randint(xmin, int((2 * ymax - xmin) / 2)))
z[0] = int(random.randint(xmin, int((2 * zmax - xmin) / 2)))
def Fxyz(self):
return ((y[0]**2)*(y[0]*z) + (x[0]*y[0] + 2*y[0])*(y[0]**3))
def fx(self):
return y[0]**4
def fy(self):
return (3*(y[0]**2)*z[0] + 11*(y[0]**1))
def fz(self):
return y[0]**3
print("Start x = " + str(x[0]))
print("y = " + str(y[0]))
print("z = " + str(z[0]))
print("Choosе:\n\t1) Find min\n\t2) Find max\n\t3) End program")
choice = int(input())
if choice == 3:
pass
elif choice == 1:
while (True):
x[1] = x[0] - h * fx(y[0])
y[1] = y[0] - h * fy(y[0], z[0])
z[1] = z[0] - h * fz(y[0])
I can't find mistake, googled every possible forum etc.. Help please.
Error from console:
Traceback (most recent call last):
File "E:\Рабочий стол\#PROJECTS\Programming\яп\лаба 2\lab2.py", line 44, in <module>
x[1] = x[0] - h * fx(y[0])
IndexError: list assignment index out of range

NoneType error with Python class and function

Despite my function returning an array, I get an TypeError: 'NoneType' object is not callable error. I first define classes, and then insert the function.
I'm relatively new to Python, and would appreciate any help/comments.
The Classes are:
from scipy import array, dot, zeros, empty
from scipy.optimize import brentq
from numpy import *
from numpy.random import uniform
from time import time
# from mpi4py import MPI
class UtilTheory:
"""
"""
def utility(self, other):
raise NotImplementedError("You need to implement method 'utility' "
"in the child class.")
def demand(self, p):
raise NotImplementedError("You need to implement method 'demand' "
"in the child class.")
def excessDemand(self, p):
p = array(p)
return self.demand(p) - self.endowment
def indUtility(self, p):
x = self.demand(p)
return self.utility(x)
def __add__(self, other):
economy = Economy([self, other])
return economy
def __radd__(self, other):
economy = Economy([self] + other)
def __rmul__(self, other):
economy = Economy(other * [self])
return economy
class Consumer(UtilTheory, object):
"""
Defines general features of a consumer
"""
def __init__(self, endowment=array([1,1]), alpha=0.5, rho=0.0):
self.endowment = array(endowment)
self.alpha = float(alpha)
self.rho = rho
self.sigma = 1.0 / (1.0 - rho)
def __str__(self):
return ('e=' + str(self.endowment) +
', alpha=' + str(self.alpha) +
', rho=' + str(self.rho))
def demand(self, p):
endowment = self.endowment
alpha = self.alpha
sigma = self.sigma
p = array(p)
m = dot(endowment, p)
x1 = ((alpha / p[0]) ** sigma * m /
(alpha ** sigma * p[0] ** (1 - sigma) +
(1 - alpha) ** sigma * p[1] ** (1 - sigma)))
x2 = (((1.0 - alpha) / p[1]) ** sigma * m /
(alpha ** sigma * p[0] ** (1 - sigma) +
(1 - alpha) ** sigma * p[1] ** (1 - sigma)))
return array([x1, x2])
def utility(self, x):
if self.rho != 0:
return ((self.alpha * x[0] ** self.rho +
(1.0 - self.alpha) * x[1] ** self.rho) **
(1.0 / self.rho))
return x[0] ** self.alpha * x[1] ** (1.0 - self.alpha)
class Economy:
"""
Consists of consumers
"""
def __init__(self, consumers):
"""
Consumers should be a list of consumers
"""
self.consumers = consumers
def excessDemand(self, p):
result = zeros(2)
for consumer in self.consumers:
result = result + consumer.excessDemand(p)
return result
def demand(self, p):
result = zeros(2)
for consumer in self.consumers:
result = result + consumer.demand(p)
return result
def excessDemandGood0(self, p0):
p = array([p0, 1.0 - p0])
result = 0
for consumer in self.consumers:
result = result + consumer.excessDemand(p)[0]
return result
def __add__(self,other):
try:
return Economy(self.consumers + other.consumers)
except:
return Economy(self.consumers + [other])
def numEquilibria(self, n=100):
# p = array([p0, 1 - p0])
q = linspace(0, 1, n)
result = empty(len(q))
#print result
for i, p0 in enumerate(q):
a = self.excessDemandGood0(p0)
#print a
result[i] = a
index = zeros(len(q))
for i in range(1, 2):
if result[i] <= 0:
index[i - 1] = 1
else:
index[i - 1] = 0
for i in range(2, n - 1):
test=result[i - 1] * result[i]
#print test
if test <= 0:
index[i - 1] = 1
else:
index[i - 1] = 0
for i in range(n - 2, n - 1):
if result[i] > 0:
index[i - 1] = 1
else:
index[i - 1] = 0
count = sum(index)
# print "The number of equilibria is"
return count
# print "Excess Demand funciton on the grid:"
# print result
# print "Index when excess demand goes from possitive to negative"
# print index
def __rmul__(self, other):
economy = Economy(other * self.consumers)
return economy
def equilibrium(self, startbracket=None):
def g(x):
return self.excessDemandGood0(x)
if startbracket == None:
startbracket = [1e-10, 1-1e-10]
eqPrice1 = brentq(g, startbracket[0], startbracket[1])
return array([eqPrice1, 1 - eqPrice1])
def __len__(self):
return len(self.consumers)
def __str__(self):
resultString = 'Economy with ' + str(len(self)) + ' consumers.\n'
for consumer in self.consumers:
resultString = resultString + str(consumer) + '\n'
return resultString
I get the error when implementing the following stats() function which calls on randomEconEq():
def randomEcon(e1=[1, 0], e2=[0, 1], iterate_max=100):
rho1 = random.uniform(-8, -1)
rho2 = random.uniform(-8, -1)
alpha1 = random.uniform(0, 1)
alpha2 = random.uniform(0, 1)
x = Consumer(endowment=e1, alpha=alpha1, rho=rho1)
y = Consumer(endowment=e2, alpha=alpha2, rho=rho2)
econ = Economy([x, y])
return econ
def randomEconEq(iterate_max=100):
iterate = 0
eq_vec = []
start = time()
while iterate < iterate_max:
iterate += 1
econ = randomEcon()
equilibria = econ.numEquilibria()
eq_vec.append(equilibria)
# print eq_vec
if (econ.numEquilibria() > 1):
print "Number of multiple equilibria is " + \
str(econ.numEquilibria())
print str(econ)
print str(eq_vec)
end = time()
totaltime = end - start
#print('Total Time is ' + str(totaltime))
return eq_vec
def stats(eq_vec, iterate_max):
one_eq = zeros(len(eq_vec))
three_eq = zeros(len(eq_vec))
five_eq = zeros(len(eq_vec))
more_eq = zeros(len(eq_vec))
# print (eq_vec)
for i in range(len(eq_vec)):
if eq_vec[i] == 1:
one_eq[i] = 1
if eq_vec[i] == 3:
three_eq[i] = 1
if eq_vec[i] == 5:
five_eq[i] = 1
if eq_vec[i] > 5:
more_eq[i] = 1
Eq1 = sum(one_eq)
Eq3 = sum(three_eq)
Eq5 = sum(five_eq)
EqMore = sum(more_eq)
prob1 = float((Eq1 / iterate_max) * 100)
prob3 = float((Eq3 / iterate_max) * 100)
prob5 = float((Eq5 / iterate_max) * 100)
probMore = float((EqMore/iterate_max) * 100)
print ('The Vector of the number of equililbria is:' + str(eq_vec))
print ('Probability of 1 equilibrium is (percent) ' + str(prob1))
print ('Probability of 3 equilibria is (percent) ' + str(prob3))
print ('Probability of 5 equilibria is (percent) ' + str(prob5))
print ('Probability of 1 equilibria is (percent) ' + str(probMore))
eq_vec = randomEconEq(100)
stats(eq_vec, 100)
The error appears in the last two lines of code when implementing the function stats().
An example which creates the error is:
stats(randomEconEq(100), 100)
and the complete traceback is:
>>> stats(randomEconEq(100), 100)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not callable

Python TypeError: unsupported operand type(s) for /: 'NoneType' and 'float'

This is a assignment we got from our teacher. We are supposed to use Simpson's Rule to do a numerical integration of a functions f(x) = x*cos(third_root(x))
But we are not allowed to use the built in function of cos or use x**(1.0/3.0) to find the third root.
I get the errors:
Traceback (most recent call last):
File "path", line 104, in <module>
print simpson(f, 1.0, 50.0, 10)
File "path", line 91, in simpson
I += 2 * f(x) + (4.0 * f(x + h))
File "path", line 101, in f
return x*final_cos(final_3root(x))
File "path", line 72, in final_cos
x = float_mod(x, 2 * pi)
File "path", line 42, in float_mod
k = int(x / a)
TypeError: unsupported operand type(s) for /: 'NoneType' and 'float'
Process finished with exit code 1
And here is my code:
import math
def final_3root(a):
q, m = math.frexp(a)
if 0.5 > q or q > 1.0:
raise ValueError('Math domain error')
x = 0.8968521468804229452995486
factor_1 = 0.6299605249474365823836053
factor_2 = 0.7937005259840997373758528
q_croot = (q / (x * x) + 2.0 * x) / 3.0
q_croot = (q / (q_croot * q_croot) + 2.0 * q_croot) / 3.0
q_croot = (q / (q_croot * q_croot) + 2.0 * q_croot) / 3.0
q_croot = (q / (q_croot * q_croot) + 2.0 * q_croot) / 3.0
if m % 3.0 == 0.0:
m /= 3
answer = math.ldexp(q_croot, m)
elif m % 3 == 1:
m += 2
m /= 3
answer = factor_1 * math.ldexp(q_croot, m)
elif m % 3 == 2:
m += 1
m /= 3
answer = factor_2 * math.ldexp(q_croot, m)
fasit = a ** (1.0 / 3.0)
#----------------------------------------------
def float_mod(x, a):
k = int(x / a)
if (x * a) < 0:
k -= 1
return x - float(k) * a
def ratio_based_cosinus(x):
epsilon = 1.0e-16
previous_Value = 1
return_Value = 1
n = -1
while True:
n += 1
ratio = (-x * x) / (((2 * n) + 1) * ((2 * n) + 2))
previous_Value *= ratio
return_Value += previous_Value
if abs(previous_Value) < epsilon:
break
return return_Value
def final_cos(x):
if isinstance(x, int):
x += 0.0
pi = 3.1415926
x = float_mod(x, 2 * pi)
if x > pi:
return ratio_based_cosinus(-x)
else:
return ratio_based_cosinus(x)
#----------------------------------------------
def simpson(f, a, b, N):
if N & 1:
raise ValueError('Ugyldig tall')
I = 0
h = float((b - a) / N)
x = float(a)
for i in range(0, N / 2):
I += 2 * f(x) + (4.0 * f(x + h))
x += 2 * h
I += float(f(b) - f(a))
I *= h / 3
print "The sum is: ", I
def f(x):
return x*final_cos(final_3root(x))
print simpson(f, 1.0, 50.0, 10)
final_3root is missing a return statement.
Look closely at the error. x is None. If you trace it back, you'll see that the return value of that function is used, but it never returns anything.

Virtual Neural Network in Python

I just wrote up a simple neural network in python as I have been studying them recently. I am using backpropogation. The activation function is a sigmoid. The inputs and weights generate randomly and the ideal output is 0. I am new to python so the code is written very inefficiently, but it is readable. When I run the code, the output is always zero and I can't seem to find why. Also, I didn't use a module.
from random import uniform
input_one_input_value = 1
input_two_input_value = 0
bias_value = 1
#use global to globalize function-based variables
#use lists to store data in future
def hidden_One():
global weighted_sum_hidden_one
weighted_sum_hidden_one = (input_one_input_value * weights[0]) + (input_two_input_value * weights[1]) + (bias_value * weights[2])
hidden_one_output = activation(weighted_sum_hidden_one)
return hidden_one_output
def hidden_Two():
global weighted_sum_hidden_two
weighted_sum_hidden_two = (input_one_input_value * weights[3]) + (input_two_input_value * weights[4]) + (bias_value * weights[5])
hidden_two_output = activation(weighted_sum_hidden_two)
return hidden_two_output
def output_One():
weighted_sum = (hidden_One() * weights[6]) + (hidden_Two() * weights[7]) + (bias_value * weights[8])
return activation(weighted_sum)
def activation(x):
sigmoid_value = 1 / (1+(2.71828 ** x))
return sigmoid_value
def calculate_gradient():
E = ideal_output - actual_output
output_delta = -E * activation(weights[6] + weights[7] + weights[8])
h1_delta = activation(weighted_sum_hidden_one) * weights[6] * output_delta
h2_delta = activation(weighted_sum_hidden_two) * weights[7] * output_delta
b2_delta = activation(bias_value) * weights[8] * output_delta
i1_delta = activation(input_one_input_value) * ((weights[0] * h1_delta) + (weights[3] * h2_delta))
i2_delta = activation(input_one_input_value) * ((weights[1] * h1_delta) + (weights[4] * h2_delta))
b1_delta = activation(bias_value) * ((weights[2] * h1_delta) + (weights[5] * h2_delta))
global w1_gradient
global w2_gradient
global w3_gradient
global w4_gradient
global w5_gradient
global w6_gradient
global w7_gradient
global w8_gradient
global w9_gradient
w1_gradient = input_one_input_value * h1_delta
w2_gradient = input_two_input_value * h1_delta
w3_gradient = bias_value * h1_delta
w4_gradient = input_one_input_value * h2_delta
w5_gradient = input_two_input_value * h2_delta
w6_gradient = bias_value * h2_delta
w7_gradient = hidden_One() * output_delta
w8_gradient = hidden_Two() * output_delta
w9_gradient = bias_value * output_delta
def backpropogation():
E = .7 #learning rate
a = .3 #momentum to prevent settling for local minima
global weightchanges_previous
global weight_change
weightchanges_previous = []
weight_change = []
if len(weightchanges_previous) == 0:
weight_change.append((E * w1_gradient))
weight_change.append((E * w2_gradient))
weight_change.append((E * w3_gradient))
weight_change.append((E * w4_gradient))
weight_change.append((E * w5_gradient))
weight_change.append((E * w6_gradient))
weight_change.append((E * w7_gradient))
weight_change.append((E * w8_gradient))
weight_change.append((E * w9_gradient))
weightchanges_previous.append(weight_change[0])
weightchanges_previous.append(weight_change[1])
weightchanges_previous.append(weight_change[2])
weightchanges_previous.append(weight_change[3])
weightchanges_previous.append(weight_change[4])
weightchanges_previous.append(weight_change[5])
weightchanges_previous.append(weight_change[6])
weightchanges_previous.append(weight_change[7])
weightchanges_previous.append(weight_change[8])
elif len(weightchanges_previous) != 0:
weight_change[0] = (E * w1_gradient) + (a * weightchanges_previous[0])
weight_change[1] = (E * w2_gradient) + (a * weightchanges_previous[1])
weight_change[2] = (E * w3_gradient) + (a * weightchanges_previous[2])
weight_change[3] = (E * w4_gradient) + (a * weightchanges_previous[3])
weight_change[4] = (E * w5_gradient) + (a * weightchanges_previous[4])
weight_change[5] = (E * w6_gradient) + (a * weightchanges_previous[5])
weight_change[6] = (E * w7_gradient) + (a * weightchanges_previous[6])
weight_change[7] = (E * w8_gradient) + (a * weightchanges_previous[7])
weight_change[8] = (E * w9_gradient) + (a * weightchanges_previous[8])
while len(weightchanges_previous) > 0 : weightchanges_previous.pop()
weightchanges_previous.append((E * w1_gradient) + (a * weightchanges_previous[0]))
weightchanges_previous.append((E * w2_gradient) + (a * weightchanges_previous[1]))
weightchanges_previous.append((E * w3_gradient) + (a * weightchanges_previous[2]))
weightchanges_previous.append((E * w4_gradient) + (a * weightchanges_previous[3]))
weightchanges_previous.append((E * w5_gradient) + (a * weightchanges_previous[4]))
weightchanges_previous.append((E * w6_gradient) + (a * weightchanges_previous[5]))
weightchanges_previous.append((E * w7_gradient) + (a * weightchanges_previous[6]))
weightchanges_previous.append((E * w8_gradient) + (a * weightchanges_previous[7]))
weightchanges_previous.append((E * w9_gradient) + (a * weightchanges_previous[8]))
def edit_weights():
weights[0] += weight_change[0]
weights[1] += weight_change[1]
weights[2] += weight_change[2]
weights[3] += weight_change[3]
weights[4] += weight_change[4]
weights[5] += weight_change[5]
weights[6] += weight_change[6]
weights[7] += weight_change[7]
weights[8] += weight_change[8]
while len(weight_change) > 0 : weight_change.pop()
weights = []
x = 0
while x <=8:
weights.append(uniform(-10, 10))
x += 1
ideal_output = 0
actual_output = output_One()
print "Output %d" % output_One()
x = 0
while x <= 10:
output_One()
calculate_gradient()
backpropogation()
edit_weights()
print "Output %d" % output_One()
print "----------------------"
actual_output = output_One()
x += 1
print "FINAL WEIGHTS:"
print weights[0]
print weights[1]
print weights[2]
print weights[3]
print weights[4]
print weights[5]
print weights[6]
print weights[7]
print weights[8]
Your problem is the output line:
print "Output %d" % output_One()
You're using %d which prints integer values so it rounds float values down to the nearest integer (integer conversion). Use %f instead and you should get the floating point numbers correctly.

Categories