-
-
Save EricSchles/dd3275f05171eefd8569bbb9530b0f7b to your computer and use it in GitHub Desktop.
code improvement exercise: solver.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from numpy.random import random | |
from numpy import array, isclose, zeros_like, sign | |
from numpy.linalg import lstsq | |
def solve(func, values, atol=0.1): | |
while True: | |
result = func(values) | |
if isclose(result, 0, atol=atol): | |
break | |
values -= sign(result) * random(values.size) | |
return values | |
def linear(coeffs, constant): | |
return lambda values: (coeffs * values).sum() + constant | |
if __name__ == '__main__': | |
coeffs = array([1., 2., 3., 4., 5.]) | |
constant = 7 | |
eq = linear(coeffs, constant) | |
print('With `solve`:') | |
vs = solve(eq, zeros_like(coeffs), atol=1e-4) | |
print(f'vs = {", ".join(f"{v:.4f}" for v in vs)}') | |
print(f'eq(vs) = {eq(vs):.4f}') | |
print() | |
vs, _, _, _ = lstsq([coeffs], [-constant], rcond=None) | |
print('With `numpy.linalg.lstsq`:') | |
print(f'vs = {", ".join(f"{v:.4f}" for v in vs)}') | |
print(f'eq(vs) = {eq(vs):.4f}') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment