-1

I have problem with approximation in python. I have a function, which gives me a dict with results. For example {1: 0.5, 2: 0.25}. It means that f(1)==0.5, f(2)==0.25, etc.

Below is what I do after getting values from my function.

lists = sorted(resultsDict.items())
x, y = zip(*lists)
startvalues = [0.5,1.0,0]
popt, pcov = curve_fit(func, x, y,p0)
function=func(x,popt[0],popt[1],popt[2])
plt.plot(x,y,'x',x,function,'r-')
plt.show()

And now I have answer. If I define function func in that way everything is OK.

def func(x,a,b,c):
   return  a+b/x

If I define that way

def func(x,a,b,c):
   return  a+b/x+c*x

I have error:

TypeError: 'numpy.float64' object cannot be interpreted as an integer

And if I define that way

def func(x,a,b,c):
   return  a+b/x+c/(x*x) # or x**2

I have error:

TypeError: can't multiply sequence by non-int of type 'tuple'

I don't know, where is a problem especially in second one and I don't know how can I dodge problem in third one if I wanted to check function 1/x**2.

martineau
  • 99,260
  • 22
  • 139
  • 249

1 Answers1

0

The first two lines of your code render x and y as tuples which act different than numpy arrays to mathematical operators. All you need to do is: x,y=np.array(sorted(resultsDict.items())).T This makes a numpy array for you, then transpose it so it has 2 rows and n columns, so it can be unpacked onto x,y.

anishtain4
  • 1,861
  • 1
  • 13
  • 15