Last active
September 5, 2020 02:40
-
-
Save soupglasses/f682038142bb5338cf22a7d7459c833d to your computer and use it in GitHub Desktop.
Quadratic formula solver using Python and Decimal precision for calculations
This file contains hidden or 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
| 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() |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example usage: