I've got a function and a set of points. The function is:
s(t) = m*g*t/k-(m*m/(k*k))*(exp(-k*t/m)-1)
where m
and k
are the parameters in question.
I have the data for (t, s(t))
I need to find the best m
and k
to fit this equation to my data, and I have little programming experience.
It seemed easier in R
:
df<-read.table("freefall2.txt", header = FALSE, sep = '\t',
strip.white = TRUE, na.strings = "empty")
time<-c(df[1])
position<-c(df[3])
fallData<-data.frame(t=time, position=c(df[3]))
plot(fallData)
m<-60
k<-1
secs=c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20)
ft=c(16,62,138, 242, 366, 504, 652, 808, 971,
1138, 1309, 1483, 1657, 1831, 2005, 2179, 2353, 2527, 2701, 2875)
jitter(secs)
jitter(ft)
fit<-nls(ft~(m*g*secs/k)+(m^2/k^2)*(exp(-k*secs/m)-1),start = list(k=k,m=m))
That was the best try, but it throws:
Error in nlsModel(formula, mf, start, wts) :
singular gradient matrix at initial parameter estimates
The Python code:
def func(t,m,k):
g=32.174
return m*g*t/k-(m*m/(k*k))*(np.exp(-k*t/m)-1)
def plotone():
plt.plot(D[0], D[2], 'b-', label='data')
popt, pcov = curve_fit(func, D[0], D[2])
plt.plot(D[0], func(D[0], *popt), 'r-', label='fit')
popt, pcov = curve_fit(func, D[0], D[2], bounds=(0, [120, 120]))
plt.plot(D[0], func(D[0], *popt), 'g--', label='fit-with-bounds')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.show()
It generated a linear model and did not return the needed parameter values.
Rebooted attempt in Python with extensive recipe sampling:
x = D[0]
y = D[2]
ycount = 0
fitfunc = lambda t, m, k: m*32.174*t/k-(m*m/(k*k))*(np.exp(-k*t/m)-1) # Target function
errfunc = lambda t, m, k: fitfunc(t, m, k) - y[ycount]; ycount+=1# Distance to the target function
p0 = [-15., 0.8, 0., -1.] # Initial guess for the parameters
p1, success = optimize.leastsq(errfunc, D[2], args=(x, y))
print(type(p1))
print(type(success))
print(p1, success)
This one looks more promising, but I understand maybe 1/2
of it. The parts I do not understand are what I am looking at when I plot it, how to feed it my model function, what success is, and a slew of other issues.
If someone says this will work if you do x
, y
, and z
, I will do it but otherwise I'd like to steer clear of this one since it's more involved and I have little time.
Please help me fit these parameters to my model function. I am so confused.