Search code examples
pythonnumpypolynomial-approximations

python numpy (v1.15.0) fails to fit parabola


I'm having trouble understanding why is numpy having such a hard time fitting parabola to this data ?

def make_poly(x, coefs):
    # generate a polynomial from an array of coefficients
    f = numpy.zeros(len(x))
    for i in range(len(coefs)):
        f = f + coefs[-1-i]*x**i
    return(f)


xx = [1443.56, 1443.56, 1450.83, 1447.59, 1454.9, 1434.77, 1423.74, 1426.87, 1438.75, 1447.59, 1454.9, 1444.36, 1454.9, 1426.09, 1454.08, 1453.27, 1447.59, 1449.2, 1451.64, 1454.08, 1454.08, 1454.9, 1454.9, 1455.71, 1452.45, 1450.01, 1453.27, 1430.81, 1454.9, 1448.39, 1432.39, 1452.45, 1445.16, 1431.6, 1447.59, 1447.59, 1425.3, 1443.56, 1453.27, 1424.52, 1429.23, 1421.4, 1454.08, 1445.97, 1427.66, 1429.23, 1433.18, 1430.81, 1440.35,1429.23]

yy = [120.15, 120.15, 123.09, 122.07, 123.52, 116.35, 104.75, 108.34, 119.13, 122.07, 124.27, 120.29, 124.27, 106.6, 124.27, 124.13, 122.07, 122.2,  122.34, 123.37, 124.27, 124.27, 124.27, 124.41, 122.34, 122.2,  123.24, 111.95, 124.27, 121.31, 113.71, 123.24, 121.18, 113.71, 121.31, 122.07, 106.6,  121.04, 124.13, 105.61, 110.96, 100.31, 123.37, 121.18, 109.21, 111.83, 114.58, 112.83, 118.38, 110.96]

fit_result = numpy.polyfit(x=xx, y=yy, deg=2, full=True)
newX = numpy.linspace(1420, 1460, 100)
pyplot.scatter(xx, yy)
pyplot.plot(newX, make_poly(newX, fit_result[0]), 'g', linewidth =.5)
pyplot.show()

Running this also throws the message:

Python(35100,0x7fff9cda3380) malloc: *** mach_vm_map(size=18446744072151506944) failed (error code=3)
*** error: can't allocate region
*** set a breakpoint in malloc_error_break to debug
init_dgelsd failed init

I am running this on OS High Sierra, Python 3.7.0, numpy 1.15.0 (installed using homebrew).


Solution

  • The code provided in the sample works well. So, I suppose the problem is laying in the packages versions state. Likely to fix the error you have to ensure that wheel, setuptools and pip + the packages you are using is up to date. Use the commands below for that:

    pip install --upgrade pip setuptools wheel
    pip install -I numpy matplotlib # + Other packages.
    

    After completing installation retry. If the error persist, please extend question with the versions of the python and packages you are using ( so it shall became reproducible).

    Update:

    The answer above has fixed the problem, especially the upgrading numpy from the 1.15.0 to 1.15.1