0

When I run my code I receive the error "unsupported operand type(s) for ** or pow(): 'numpy.ufunc' and 'float'"

The code is:

import numpy as np
import matplotlib.pyplot as plt
from numpy import sqrt,exp,log
from scipy import linalg
from scipy.optimize import curve_fit

data1 = np.loadtxt('decay1.txt', float,skiprows=1)
t = data1[:,0]
n = data1[:,1]

data2 = np.loadtxt('decay2.txt', float,skiprows=1)
T = data2[:,0]
N = data2[:,1]

def Radio(n,t,tao,b):
    return (n*(exp**(-(t/tao)))) + b

guesses = (1,1,1)
guesses2 = (1,1,1)

(p0,p1,p2),cc = curve_fit(Radio,t,n,guesses)
(p02,p12,p22),cc2 = curve_fit(Radio,T,N,guesses2)

yfit = Radio(t,p0,p1,p2)
y2fit = Radio(T,p02,p12,p22)

I have to fit the function to the radioactive decay data, so tell me if I also messed up the code to fit a function to it. Thanks for any help!

2
  • with respect to your second question, I have not used scipy.optimize, but from the docs it looks right to me, with the exception that I think you switched the order of inputs between the function (n,t) and the curve fit (t,n) Commented Apr 28, 2018 at 5:17
  • I take that back, looks like there is a problem in the formulation. Will edit my answer with description Commented Apr 28, 2018 at 5:22

1 Answer 1

1

numpy.exp is the exponential function and ** is the power operator, so you're trying to raise a function definition to the power (-(t/tao)). I think you wanted

def Radio(n,t,tao,b):
    return (n*(exp(-(t/tao)))) + b

With respect to the use of the optimization function, there are a couple of issues. First, you are using n as both the parameter (inside the Radio method) and the dependent variable data (from the problem statement), which is confusing things. I would change that to something like a (as is used in the curve_fit doc. That's not really necessary, but helps readability.

Second, and more importantly, the function to be fit must have the independent variable (in this case, t) as the first argument. I think what is happening to cause a flat fit is that you are actually fitting the curve n->Radio(n) (with all those other variables as parameters) instead of t->Radio(t).

Sign up to request clarification or add additional context in comments.

2 Comments

Oh wow! thanks a ton haha, how do I select this as the answer?
@BrandonSeedlessBananasMc-Wil updated with potential fix for the curve fit

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.