On Aug 29, 4:50 am, Oscar Gerardo Lazo Arjona <algebraicame...@gmail.com> wrote: > Hello! > > I have tried to fit some data about an harmonic oscillator to a sine > function, but without success. > > Well, the find_fit command does return the values of constants, but they > don't fit the data at all! > > I've attatched a worksheet showing this. The first cells are for > retrieving the data from a file, just look at the two plots and how the > fitted function (in red) doesn't match the data at all... > > Any ideas? > > Thanks > > Oscar
Basically, the find_fit function has problems to find a good initial guess (especially for the period) You could try to help it. I can see two ways to do it, using the fact that you expect a sin function. First, guess the parameters yourself: you could look for sign changes to guess the period, this would give you: sage: initial_omega = pi.n()/mean(differences([0.5*(data1[i][0]+data1[i +1][0]) for i in range(len(data1)-1) if data1[i][1]*data1[i+1][1] < 0])) it seems to be enough: sage: fit=find_fit(data1,model,parameters=[x0,omega,phi],initial_guess=[1, omega_i, 1],solution_dict=True); fit {x0: 0.051021428637755981, phi: -0.021166741696878096, omega: 9.521221611651983} (nb: you could also find youself better initial guesses for the other parameters: x0_i = max([y for x,y in data1]) phi_i = sorted(data1, key=lambda t:abs(t[1]))[0][1] ) Second possibility, "clean the data", it would be a lot easier if we have only one period: sage: min(i for i,(x,y) in enumerate(data1) if y*data1[0][1]<0) # first sign change 17 sage: min(i for i,(x,y) in enumerate(data1) if y*data1[0][1]<0) # second sign change 34 sage: data2 = data1[17:34] sage: fit2=find_fit(data2,model,solution_dict=True); fit2 {x0: 0.05240254787043807, phi: 6.2763562528486139, omega: 9.5651019068351939} You can even go back to data1: sage: fit=find_fit(data1,model,parameters=[x0,omega,phi],initial_guess=[fit2[x0], fit2[omega], fit2[phi]],solution_dict=True); fit {x0: 0.051021428642885822, phi: 6.2620185789145335, omega: 9.5212216134899759} -- To post to this group, send email to sage-support@googlegroups.com To unsubscribe from this group, send email to sage-support+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/sage-support URL: http://www.sagemath.org