Say I want to fit two arrays x_data_one
and y_data_one
with an exponential function. In order to do that I might use the following code (in which x_data_one
and y_data_one
are given dummy definitions):
import numpy as np
from scipy.optimize import curve_fit
def power_law(x, a, b, c):
return a * (x + c) ** b
x_data_one = np.random.rand(10)
y_data_one = np.random.rand(10)
(a_one, b_one, c_one), _ = curve_fit(power_law, x_data_one, y_data_one)
Now suppose I want to fit a second dataset:
x_data_two = np.random.rand(10)
y_data_two = np.random.rand(10)
(a_two, b_two, c_two), _ = curve_fit(power_law, x_data_two, y_data_two)
How could I perform these two fits such that they were constrained to have a_one == a_two
and b_one == b_two
, but not necessarily c_one == c_two
? I don't want to constrain a_one
or b_one
to a particular value; I want to find values that provide the best fit for both datasets.
You could simply overwrite your function for the second data set:
Or you could use this (it finds optimal a,b for all data and optimal c1 for data_one and c2 for data_two):
In my opinion second code much nicer and pythonic :)