Skip to content

Instantly share code, notes, and snippets.

@soupglasses
Last active September 5, 2020 02:40
Show Gist options
  • Save soupglasses/f682038142bb5338cf22a7d7459c833d to your computer and use it in GitHub Desktop.
Save soupglasses/f682038142bb5338cf22a7d7459c833d to your computer and use it in GitHub Desktop.
Quadratic formula solver using Python and Decimal precision for calculations
import click
from decimal import Decimal, getcontext
@click.command()
@click.argument('a', type=click.FLOAT)
@click.argument('b', type=click.FLOAT)
@click.argument('c', type=click.FLOAT)
@click.option('--precision', '-p', type=click.INT, help='Decimal precision by number')
def main(a,b,c,precision):
"""Quadratic formula solver"""
if not precision:
precision = 3
getcontext().prec = precision
a,b,c = Decimal(a), Decimal(b), Decimal(c)
try:
top = ((b*b) - (4*a*c)).sqrt()
bottom = (2*a)
x1 = (((-b) + top) / bottom )
x2 = (((-b) - top) / bottom )
except:
print(f"No valid solution for a={a}, b={b}, c={c}.")
else:
if x1 == x2:
print(f"x0={x1}")
else:
print(f"x1={x1}\tx2={x2}")
if __name__ == '__main__':
main()
@soupglasses
Copy link
Author

soupglasses commented Aug 4, 2020

Example usage:

$ python quadratic.py 2 5 3
x1=-1	 x2=-1.5
$ python quadratic.py 4 12 9
x0=-1.5
$ python quadratic.py 3 2 1
Found no valid solution for a=3, b=2, c=1.
$ python quadratic.py 2 5 1
x1=-0.22	 x2=-2.28
$ python quadratic.py 2 5 1 -p 6
x1=-0.219222	 x2=-2.28078

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment