我们必须通过拍摄钟摆来进行运动检测,使用给定的软件跟踪钟摆并将 t、x 和 y 值存储在 txt 文件中。由于我的手很抖,所以图表也很抖(附图)。
这是我的代码:
import sys
sys.path.insert(0, "..")
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
%matplotlib inline
import pandas as pd
data = np.loadtxt('newdata.txt', delimiter = ',', skiprows = 1)
t = data[:,0]
x = data[:,1]
def cos_func(times, amplitude, frequency):
return amplitude * np.cos(frequency * times)
def period2freq(period):
return 1.0 / period * 2.0 * np.pi
def freq2period(freq):
return 1.0 / freq * 2.0 * np.pi
popt, pcov = curve_fit(cos_func, # our function
t, # measured x values
x, # measured y values
p0=(200, period2freq(150))) # the initial guess for the two parameters
fig, ax = plt.subplots(1, 1)
ax.plot(t, x, label='Measured')
ax.plot(t, cos_func(t, popt[0], popt[1]), label='Best Fit')
ax.legend()
我尝试了所有我能想到的方法,但我是个菜鸟
您是否尝试过将功能更改为:
def cos_func(times, amplitude, frequency, offset):
return amplitude * np.cos(frequency * times) + offset