x = Symbol ("x")
f = log(x)
dif1 = diff(f,x)
dif2 = diff(dif1,x)
dif3 = diff(dif2,x)
dif4 = diff(dif3,x)
dif5 = diff(dif4,x)
def D11(a,h):
return (f.evalf(subs={x:a+h})-f.evalf(subs={x:a}))/h + (h/2)*dif2.evalf(subs={x:a+h/2})
def D12(a,h):
return ((f.evalf(subs={x:(a+h)}) - f(a-h)))/(2*h) - h**2/6*dif3.evalf(subs={x:(a)})
def D13(a,h):
return (f.evalf(subs={x:(a-2*h)})- 8*f.evalf(subs={x:(a-h)}) + 8*f.evalf(a+h) - f(a+2*h))/(12*h) - h**4/30*ftuletis5(a)
def D22(a,h):
return (f.evalf(subs={x:(a+h)}) - 2*f.evalf(subs={x:(a)}) + f.evalf(subs={x:(a-h)}))/h**2 - h**2/12*(dif4.evalf(subs={x:(a)}))
vigaD11 = []
vigaD12 = []
vigaD13 = []
vigaD22 = []
h=[]
for i in range(20):
h+=h+[(10**(-i))]
vigaD11+= vigaD11 + [(D11(2,h[i])-(dif1.evalf(subs={x:2})))]
vigaD12+= vigaD12+[(D12(2,h[i])-(dif1.evalf(subs={x:2})))]
vigaD13+= vigaD13 + [(D13(2,h[i])-(dif1.evalf(subs={x:2})))]
vigaD22+= vigaD22 [(D22(2,h[i])-(dif2.evalf(subs={x:2})))]
I get an error message saying that log object is not callable. Currently I'm using the math package and Sympy package to get the program to do what I want.
The error message I get:
Traceback (most recent call last):
File "C:\Users\arman\Desktop\Numbrilised meetodid\praktikum12\praktikum12.py", line 64, in <module>
vigaD12+= vigaD12+[(D12(2,h[i])-(dif1.evalf(subs={x:2})))]
File "C:\Users\arman\Desktop\Numbrilised meetodid\praktikum12\praktikum12.py", line 37, in D12
return ((f.evalf(subs={x:(a+h)}) - f(a-h)))/(2*h) - h**2/6*dif3.evalf(subs={x:(a)})
TypeError: 'log' object is not callable
It still does not work when I specifically call out the sympy version of log. Please help.
You could try f = math.log(x) or whichever log function you want to use. Maybe python just doesn't find the right function to call.
In an isympy session with * import ofsympyandxsymbol,log` a sympy object
In [1]: log
Out[1]: log
In [2]: x
Out[2]: x
In [3]: f = log(x)
In [4]: f(23)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-4-a73e6f7d2549> in <module>
----> 1 f(23)
TypeError: 'log' object is not callable
You can't call log again; it's already been "called". You can evaluate it at specific number with:
In [13]: f.evalf(subs={x:1.23})
Out[13]: 0.207014169384326
You do that once in the problem expression, but not the second time. Why not?
f.evalf(subs={x:(a+h)}) - f(a-h)
Related
I really don't understand what causes the problem, could someone point it out for me please?
with shelve.open(obj_path) as obj:
for as_num in obj['as_number_list']: # ignore warning, obj['as_number_list'] is a list
temp = charge_as(obj['as_' + str(as_num)]) # temp is an object
as_test = temp # doing like this is ok
print(type(as_test))
exec("as_{}_obj = {}".format(as_num, temp)) # **error here**
And it gives syntax error like this:
<class 'instruments.AS'>
Traceback (most recent call last):
File "...", line 45, in <module>
exec("as_{}_obj = {}".format(as_num, temp))
File "<string>", line 1
as_1_obj = <instruments.AS object at 0x000002A86732E290>
^
SyntaxError: invalid syntax
I tried
exec("as_{}_obj = {}".format(as_num, temp.__dict__))
no error is shown but now as_{}_obj is of class 'dict' instead of class 'instruments.AS'
line 45:
exec("as_{}_obj = temp".format(as_num))
I'm making a program that uses derivates to calculate an error.
I keep getting this error : 'Mul' object has no attribute 'sp'.
The solutions to this error that i've found so far are when people import everything from sympy and math (from sympy/math import *) because both sympy and math have a sin() function.
But as you can see from my code bellow i don't have it like that and the error still shows up, why?
import sympy as sp
from math import factorial
def F(x):
return 4*(x**2)+sp.sin(9*x)
sp.init_printing()
x=sp.symbols('x')
def D1(x1):
return(sp.diff(F(x),x,1).sp.subs(x,x1))
def D2(x1):
return(sp.diff(F(x),x,2).sp.subs(x,x1))
def D3(x1):
return(sp.diff(F(x),x,3).sp.subs(x,x1))
def maxD3(x1,x2):
if(D3(x1)>D3(x2)):
return D3(x1)
else:
return D3(x2)
erro1 = (1/factorial(3))*maxD3(-1,1)*abs((0.3-(-1))*(0.3-1))
erro1 = (1/factorial(3))*maxD3(-1,1)*abs((0.83-(-1))*(0.83-1))
print("Erro f(0.3): ", erro1)
print("Erro f(0.83): ", erro2)
Also have changed "from math import factorial" to "import math as math" and the error also keeps showing up.
I'm using Python 3.6.1.
EDIT: Full Traceback
Traceback (most recent call last):
File "main.py", line 24, in <module>
erro1 = (1/math.factorial(3))*maxD3(-1,1)*abs((0.3-(-1))*(0.3-1))
File "main.py", line 19, in maxD3
if(D3(x1)>D3(x2)):
File "main.py", line 16, in D3
return(sp.diff(F(x),x,3).sp.subs(x,x1))
AttributeError: 'Mul' object has no attribute 'sp'
This is the corrected version of your code
import sympy as sp
from math import factorial
def F(x):
return 4*(x**2)+sp.sin(9*x)
sp.init_printing()
x=sp.symbols('x')
def D1(x1):
return(sp.diff(F(x),x,1).subs(x,x1)) # subs instead of sp.subs
def D2(x1):
return(sp.diff(F(x),x,2).subs(x,x1)) # subs instead of sp.subs
def D3(x1):
return(sp.diff(F(x),x,3).sp.subs(x,x1))
def maxD3(x1,x2):
if(D3(x1)>D3(x2)):
return D3(x1)
else:
return D3(x2)
erro1 = (1/factorial(3))*maxD3(-1,1)*abs((0.3-(-1))*(0.3-1))
erro2 = (1/factorial(3))*maxD3(-1,1)*abs((0.83-(-1))*(0.83-1)) # erro2 instead of erro1
print("Erro f(0.3): ", erro1)
print("Erro f(0.83): ", erro2)
Output on my system:
('Erro f(0.83): ', 0)
('Erro f(0.83): ', 0)
Is this the expected output?
Also, you don't need to import everything from sympy. You can just import what you need.
Example:
>>> from sympy import sin, symbols, diff
>>> x = symbols('x')
>>> f = x**3 + sin(x)
>>> print(diff(f, x))
3*x**2 + cos(x)
>>> print(diff(f, x).subs(x, 1))
cos(1) + 3
My python code was running successfully in Ubuntu 14.04; but when I went to run in Windows Platform, it throws me into error.
The Code:
import pymc
with open("days1.txt") as f:
dataset = map(float, f)
a = pymc.Uniform('a', lower=0, upper=1500000, value=70, doc='Weibull alpha parameter')
b = pymc.Uniform('b', lower=0, upper=1500000, value=70, doc='Weibull beta parameter')
like = pymc.Weibull('like', alpha=a, beta=b, value=dataset, observed=True)
if __name__=='__main__':
import pylab
M = pymc.MCMC([a,b,like])
M.sample(10000,5000,2)
pymc.Matplot.plot(a)
pymc.Matplot.plot(b)
M.summary()
M.write_csv("parameters1.csv")
The error:
C:\Python35-32>python.exe "E:\TCS\Desktop\EarlyWarning\JLR\Data\EJ327000AB\Scrip
ts\Screen 7\Check Python - 1\weibullEstimationOutData - 1.py"
Traceback (most recent call last):
File "C:\Python35-32\lib\site-packages\pymc\PyMCObjects.py", line 742, in __in
it__
self._value = np.array(value, dtype=dtype)
TypeError: float() argument must be a string or a number, not 'map'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "E:\TCS\Desktop\EarlyWarning\JLR\Data\EJ327000AB\Scripts\Screen 7\Check P
ython - 1\weibullEstimationOutData - 1.py", line 8, in <module>
like = pymc.Weibull('like', alpha=a, beta=b, value=dataset, observed=True)
AttributeError: 'TypeError' object has no attribute 'message'
Kindly Help. Thanks in Advance
You are using Python 2 with Ubuntu, but Python 3 with Windows. Install Python 2 for Windows, or port your code to Python 3
import pylab
import pymc
with open("days1.txt") as f:
dataset = list(map(float, f))
a = pymc.Uniform('a', lower=0, upper=1500000, value=70, doc='Weibull alpha parameter')
b = pymc.Uniform('b', lower=0, upper=1500000, value=70, doc='Weibull beta parameter')
like = pymc.Weibull('like', alpha=a, beta=b, value=dataset, observed=True)
if __name__=='__main__':
M = pymc.MCMC([a,b,like])
M.sample(10000,5000,2)
pymc.Matplot.plot(a)
pymc.Matplot.plot(b)
M.summary()
M.write_csv("parameters1.csv")
def h(x):
x = ((x[0])*len(x))
return x
when i print it, it goes
h(he)
Traceback (most recent call last):
File "<pyshell#45>", line 1, in <module>
h(he)
NameError: name 'he' is not defined
Do you maybe mean to pass he as a string? 'he' would be the appropriate way then.
def h(x):
x = ((x[0])*len(x))
return x
print(h('he'))
>>> hh
So I am creating a module, and I am importing it to a python shell and running some stuff to make sure all features work and such.
For some reason every time I run the code, it gives the following error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/ryansaxe/Desktop/Code/python/modules/pymaps.py", line 102, in url_maker
#anything can be here
AttributeError: type object 'datetime.datetime' has no attribute 'datetime'
So where the #anything can be here is, is whatever is on line 102 of my code. Originally line 102 was:
if isinstance(startindex,datetime.datetime):
and I got the error above. I put a quick print statement on line 102 to check and it gave the same error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/ryansaxe/Desktop/Code/python/modules/pymaps.py", line 102, in url_maker
print 'Hello'
AttributeError: type object 'datetime.datetime' has no attribute 'datetime'
Is this some sort of bug? Why is it telling me there is an error with datetime on the line print 'Hello'?
Because it may be helpful, I will give you the function I am having trouble with since I have no clue how this is possible. I am keeping the print 'Hello' line so you can see where line 102 is:
def url_maker(latitudes,longitudes,times=None,color='red',label=' ',zoom=12,center=None,start=None,end=None,by=None,size='600x300'):
urls = []
import datetime
if isinstance(times[0],str) or isinstance(times[0],datetime.datetime):
from dateutil import parser
if isinstance(times[0],str):
times = [parser.parse(x) for x in times]
if isinstance(start,str):
startindex = parser.parse(start)
else:
startindex = start
if isinstance(end,str):
endindex = parse.parse(end)
else:
endindex = end
print 'Hello'
if isinstance(startindex,datetime.datetime):
startpos = between_times(times,startindex,by='start')
elif isinstance(startindex,int):
if isinstance(endindex,datetime.datetime):
startpos = between_times(times,endindex,by='end') - start
else:
startpos = start
else:
pass
if isinstance(endindex,datetime.datetime):
endpos = between_times(times,endindex,by='end')
elif isinstance(endindex,int):
if isinstance(startindex,datetime.datetime):
endpos = between_times(times,startindex,by='start') + end
else:
endpos = end
else:
pass
else:
times = range(1,len(latitudes) + 1)
if isinstance(start,int):
startpos = start
else:
startpos = None
if isinstance(end,int):
endpos = end
else:
endpos = None
if isinstance(by,str):
lat,lon,t = latitudes[startpos:endpos],latitudes[startpos:endpos],times[startpos:endpos]
print lat
t,lats,lons = time_sample(t,by,lat,lon)
elif isinstance(by,int):
lats,lons,t = latitudes[startpos:endpos:by],latitudes[startpos:endpos:by],times[startpos:endpos:by]
else:
lats,lons,t= latitudes[startpos:endpos],latitudes[startpos:endpos],times[startpos:endpos]
print t
print len(t)
if center == None:
latit = [str(i) for i in lats]
longi = [str(i) for i in lons]
center = '¢er=' + common_finder(latit,longi)
else:
center = '¢er=' + '+'.join(center.split())
zoom = '&zoom=' + str(zoom)
for i in range(len(lats)):
#label = str(i)
x,y = str(lats[i]),str(lons[i])
marker = '&markers=color:' + color + '%7Clabel:' + label + '%7C' + x + ',' + y
url = 'http://maps.googleapis.com/maps/api/staticmap?maptype=roadmap&size=' + size + zoom + center + marker + '&sensor=true'
urls.append(url)
#print i
return urls,t
You are running with a stale bytecode cache or are re-running the code in an existing interpreter without restarting it.
The traceback code has only bytecode to work with, which contains filename and linenumber information. When an exception occurs, the source file is loaded to retrieve the original line of code, but if the source file has changed, that leads to the wrong line being shown.
Restart the interpreter and/or remove all *.pyc files; the latter will be recreated when the interpreter imports the code again.
As for your specific exception; you probably imported the datetime class from the datetime module somewhere:
from datetime import datetime
The datetime class does not have a datetime attribute, only the module does.