简体   繁体   中英

Finding an accurate mathmatical function from a plot/ 2d array?

How would i go about finding the mathmatical function from a graphical plot/ 2d array? eg

line = [0,1,2,3,4,5,6,7,8,9,10] 
print(findfunction(line))
>y=x

line2 =[5,7,9,11,13,15,17,19] 
print(findfunction(line2))
>y=2x+5

And so on for ploynomials, exponentials and everything in between.

I understand for some lines there either may be no function**, or i may have to break it down into ranges to get anything that closely resembals a function but i can't think of how to do this, aside brute force but that dosen't seem reliable.

**no function? kinda makes sense that there is a function to describe every possible line/ curve, right?

For linear equations, you could simply use NumPy's polyfit. Assuming the line arrays you mentioned have values x = 1,2,3,4... we could do the following

def fit_to_function(x, y):
    """
    fit_to_function(x, y)
    x: list of x values
    y: list of y values
    returns: list of y values that fit the function
    """
    x, b = np.polyfit(x, y, 1)
    return f"y = {x}x + {b}"

Testing:

x = [0,1,2,3,4,5,6,7]
y = [5,7,9,11,13,15,17,19]

print(fit_to_function(x, y))

Output:

y = 1.9999999999999998x + 5.000000000000003

Optional: if you want to round it like in your original question

import numpy as np

def fit_to_function(x, y):
    """
    fit_to_function(x, y)
    x: list of x values
    y: list of y values
    returns: list of y values that fit the function
    """
    x, b = np.polyfit(x, y, 1)
    x, b = round(x, 2), round(b, 2)
    return f"y = {x}x + {b}"

Output:

y = 2.0x + 5.0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM