Skip to content

Instantly share code, notes, and snippets.

@dutc
Last active June 10, 2018 03:04
Show Gist options
  • Save dutc/ee11c4de4192b21c0568cee32ce24c4e to your computer and use it in GitHub Desktop.
Save dutc/ee11c4de4192b21c0568cee32ce24c4e 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