Shaun Patel
Shaun Patel

Reputation: 11

Issue with solving offset parameter for cosine function with scipy optimize curve_fit

I am trying to solve for the phase offset of a cosine function. I am looking for a value between [0, 2*pi].

To explore this using scipy.optimize.curvefit I created a toy function, below:

import scipy.optimize as optimize
import numpy as np
import matplotlib.pyplot as plt

# DATA
angles = np.array([0, 45, 90, 135, 180, 225, 270, 315])
angles = np.radians(angles)
offset = np.radians(176)
data = np.cos(np.radians(np.linspace(0,315,8))-offset)

plt.plot(np.degrees(angles), data)

# COSINE FUNCTION
def func(theta, k, b, p):
    return b + k*np.cos(theta-(p))

# COSINE FIT
popt, pcov = optimize.curve_fit(func, angles, data)

# COSINE COMPUTATION
yn = func(angles, popt[0], popt[1], popt[2])
plt.plot(np.degrees(angles), yn, color='r', linestyle='--')
print np.degrees(popt[2])

In the example above, I create a cosine function with a phase offset of 176 degrees. When I solved for the phase offset, I received -4. I understand you can arrive to this by (180-4) but I do not understand the underlying behavior. If for example the offset was set to equal 190, the output would be 10. As a result, I don't know (without visually inspecting the curves) whether the fit is on the interval [0, pi] or [pi, 2pi].

Any advice is appreciated.

Upvotes: 1

Views: 416

Answers (1)

rickhg12hs
rickhg12hs

Reputation: 11902

Refresh your trig knowledge. You shouldn't expect 180.

Upvotes: 2

Related Questions