scipy curve_fit doesn’t like math module

Be careful with numpy-arrays, operations working on arrays and operations working on scalars!

Scipy optimize assumes the input (initial-point) to be a 1d-array and often things go wrong in other cases (a list for example becomes an array and if you assumed to work on lists, things go havoc; those kind of problems are common here on StackOverflow and debugging is not that easy to do by the eye; code-interaction helps!).

import numpy as np
import math

x = np.ones(1)

np.sin(x)
> array([0.84147098])

math.sin(x)
> 0.8414709848078965                     # this only works as numpy has dedicated support
                                         # as indicated by the error-msg below!
x = np.ones(2)

np.sin(x)
> array([0.84147098, 0.84147098])

math.sin(x)
> TypeError: only size-1 arrays can be converted to Python scalars

To be honest: this is part of a very basic understanding of numpy and should be understood when using scipy’s somewhat sensitive functions.

Leave a Comment