Skip to content

Instantly share code, notes, and snippets.

@EricSchles
Forked from dutc/solver.py
Created June 10, 2018 03:04
Show Gist options
  • Save EricSchles/dd3275f05171eefd8569bbb9530b0f7b to your computer and use it in GitHub Desktop.
Save EricSchles/dd3275f05171eefd8569bbb9530b0f7b to your computer and use it in GitHub Desktop.
code improvement exercise: solver.py
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