Search code examples
pythonvariablesapproximation

Finding coefficients for approximations


I just would like to approximate any number, out of mathematical curiosity, purely in terms of e.

Example: If I give n=7.3890, the program must return a=1,b=0, which is the best approximation(minimal error) for all whole number pairs(a,b)

from math import *
n=float(input("Enter a number to be approximated:"))
for a in range(10):
    for b in range(10):
            if ((e**2)*a)+(e*b)==n:
                print(a,b)

This program couldn't do so since it searches for exact values rather than approximate ones


Solution

  • Premise: the following solution finds integer (approximate) coefficients.

    An easy way to make your code more efficient is to use vectorization (using the numpy library) to compute the polynomial on all combination of indices, then return the combination of indices whose value of the polynomial is closer to the value of n.

    The following code creates a grid of all integer a and b combinations using np.meshgrid, then computes the polynomial on all combinations and computes the positions of the combination making the polynomial closer to n using np.argmin. Lastly, it returns the a and b values of the combination.

    import numpy as np
    
    def find_approximate_integer_coefficients(n, x, amin=-10, amax=10, bmin=-10, bmax=10):
        a_range = np.arange(amin, amax+1)
        b_range = np.arange(bmin, bmax+1)
    
        a_coefficients, b_coefficients = np.meshgrid(a_range, b_range)
        polynomial_value = (a_coefficients * (x ** 2) + b_coefficients * x)
    
        argmin = np.abs(polynomial_value - n).argmin()
        return a_coefficients.flatten()[argmin], b_coefficients.flatten()[argmin]
    

    For instance, find_approximate_integer_coefficients(7.3890, np.e) returns (1, 0) in about 75 microseconds on my laptop.

    You can easily extend the code above to the case of higher-order polynomials as the np.meshgrid method accepts an arbitrary number of ranges to create the grid.