scipy curve_fit doesn't like math module

前端 未结 1 1306
抹茶落季
抹茶落季 2020-12-04 02:43

While trying to create an example with scipy.optimize curve_fit I found that scipy seems to be incompatible with Python\'s math module. While funct

相关标签:
1条回答
  • 2020-12-04 03:23

    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.

    0 讨论(0)
提交回复
热议问题