2

I'm trying to fit a series of data to a exponential equation, I've found some great answer here: How to do exponential and logarithmic curve fitting in Python? I found only polynomial fitting But it didn't contain the step forward that I need for this question.

I'm trying to fit y and x against a equation: y = -AeBx + A. The final A has proven to be a big trouble and I don't know how to transform the equation like log(y) = log(A) + Bx as if the final A was not there.

Any help is appreciated.

Rocky Li
  • 5,641
  • 2
  • 17
  • 33

1 Answers1

6

You can always just use scipy.optimize.curve_fit as long as your equation isn't too crazy:

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

def f(x, A, B):
    return -A*np.exp(B*x) + A

A = 2
B = 1
x = np.linspace(0,1)

y = f(x, A, B)
scale = (max(y) - min(y))*.10
noise = np.random.normal(size=x.size)*scale
y += noise

fit = sio.curve_fit(f, x, y)

plt.scatter(x, y)
plt.plot(x, f(x, *fit[0]))
plt.show()

This produces:

enter image description here

tel
  • 13,005
  • 2
  • 44
  • 62
  • Interesting and nice explanation, I'll try it out. – Rocky Li Nov 13 '18 at 03:14
  • Worked! I just needed to flip B to negative because it doesn't deal with negative numbers apparently. – Rocky Li Nov 13 '18 at 03:21
  • 1
    @RockyLi Great, glad to hear it. And if you're ever bored and looking for some math to do, you may be able to derive an analytical expression for the fit using the [least-squares approach](http://mathworld.wolfram.com/LeastSquaresFitting.html). There's a [well-known closed form equation](http://mathworld.wolfram.com/LeastSquaresFittingExponential.html) for the fit of the standard exponential form `y = A*e**(B*x)` – tel Nov 13 '18 at 03:33