quadratic formula using python - python

Trying to create a program that takes in three arguments that represent the a, b, and c values in the quadratic formula. The values should be to two decimal places. You do not need to account for imaginary values. Then print out both roots in the form:
The solutions are x and y
Where x and y correspond to the positive and negative roots, respectively.
Having issues with my code:
import math
a = float(input('please input a number:'))
b = float(input('please input a number3:'))
c = float(input('please input a number2:'))
d = (b**2) - (4*a*c)
sol1 = str(round((-b-cmath.sqrt(d))/(2*a),2))
sol2 = str(round((-b+cmath.sqrt(d))/(2*a),2))
print('The solution are {1.real:.2f} and {0.real:.2f}'.format(sol1,sol2))

In your code you imported math but used cmath. But, a simpler solution would be to not import anything and use the built in power function. Also, python handles printing integers, floats, and complex numbers by itself, so you don't need to worry about casting.
Try this:
# Get inputs
a = float(input("a: "))
b = float(input("b: "))
c = float(input("c: "))
# Calculate discriminant
discriminant = b**2 - 4*a*c
# Get solutions, x^0.5 = square root
x1 = (-b + discriminant**0.5) / (2*a)
x2 = (-b - discriminant**0.5) / (2*a)
# Output
print(f"Solutions: {x1} and {x2}")

Related

How to avoid complex numbers and get floats?

this our first Homework and we struggle a problem.We try to create a code for a curve sketching, but Our problem is that we have to put some results in another function to get to our goal. We just get complex numbers for result but need floats.
How can we avoid getting complex numbers in the first place?
from sympy import *
function = input("function =") #x^5+x^4+x^3+x^2+x+1 for example
n1 = solve(function,x)
for n1 in solve(function,x):
print("n1 :",(N(n1)))
You can just check if the result is real:
from sympy import *
x = symbol.Symbol("x")
function = input("function =") #x^5+x^4+x^3+x^2+x+1 for example
n1 = solve(function,x)
for n1 in solve(function,x):
if n1.is_real:
print("n1 :",(N(n1)))
The other roots are still there, but now you only see the ones in real space.
Your example (x**5 + x**4 + x**3 + x**2 + x + 1) is a 5th order polynomial so it can have up to 5 roots. In this case there is only one real root, and the rest are complex.
Hence the output is exactly what you would expect
n1 : -1.00000000000000
n1 : -0.5 - 0.866025403784439*I
n1 : -0.5 + 0.866025403784439*I
n1 : 0.5 - 0.866025403784439*I
n1 : 0.5 + 0.866025403784439*I

(RSA) This script I got off of stackoverflow returns a negative d value

So I stumbled upon this thread on here with this script and it returns a negative d value and my p and q values are both prime. Any reason for this? Possibly just a faulty script?
def egcd(a, b):
x,y, u,v = 0,1, 1,0
while a != 0:
q, r = b//a, b%a
m, n = x-u*q, y-v*q
b,a, x,y, u,v = a,r, u,v, m,n
gcd = b
return gcd, x, y
def main():
p = 153143042272527868798412612417204434156935146874282990942386694020462861918068684561281763577034706600608387699148071015194725533394126069826857182428660427818277378724977554365910231524827258160904493774748749088477328204812171935987088715261127321911849092207070653272176072509933245978935455542420691737433
q = 156408916769576372285319235535320446340733908943564048157238512311891352879208957302116527435165097143521156600690562005797819820759620198602417583539668686152735534648541252847927334505648478214810780526425005943955838623325525300844493280040860604499838598837599791480284496210333200247148213274376422459183
e = 65537
ct = 313988037963374298820978547334691775209030794488153797919908078268748481143989264914905339615142922814128844328634563572589348152033399603422391976806881268233227257794938078078328711322137471700521343697410517378556947578179313088971194144321604618116160929667545497531855177496472117286033893354292910116962836092382600437895778451279347150269487601855438439995904578842465409043702035314087803621608887259671021452664437398875243519136039772309162874333619819693154364159330510837267059503793075233800618970190874388025990206963764588045741047395830966876247164745591863323438401959588889139372816750244127256609
# compute n
n = p * q
# Compute phi(n)
phi = (p - 1) * (q - 1)
# Compute modular inverse of e
gcd, a, b = egcd(e, phi)
d = a
print( "n: " + str(d) );
# Decrypt ciphertext
pt = pow(ct,d,n)
print( "pt: " + str(pt) )
if __name__ == "__main__":
main()
This can happen, I'll explain why below, but for practical purposes you'll want to know how to fix it. The answer to that is to add phi to d and use that value instead: everything will work as RSA should.
So why does it happen? The algorithm computes the extended gcd. The result of egcd is a*e + b*phi = gcd, and in the case of RSA, we have gcd = 1 so a*e + b*phi = 1.
If you look at this equation modulo phi (which is the order of the multiplicative group), then a*e == 1 mod phi which is what you need to make RSA work. In fact, by the same congruence, you can add or subtract any multiple of phi to a and the congruence still holds.
Now look at the equation again: a*e + b*phi = 1. We know e and phi are positive integers. You can't have all positive integers in this equation or else no way would it add up to 1 (it would be much larger than 1). So that means either a or b is going to be negative. Sometimes it will be a that is negative, other times it will be b. When it is b, then your a comes out as you would expect: a positive integer that you then assign to the value d. But the other times, you get a negative value for a. We don't want that, so simply add phi to it and make that your value of d.

Quadractic Formula mix up

So I made a python code that solves for x using the quadratic formula. Everything works out in the end except for the signs. For instance, if you want to factor x^2 + 10x + 25, my code outputs -5, -5 when the answer should be 5, 5.
def quadratic_formula():
a = int(input("a = "))
b = int(input("b = "))
c = int(input("c = "))
bsq = b * b
fourac = 4 * a * c
sqrt = (bsq - fourac) ** (.5)
oppb = -b
numerator_add = (oppb) + (sqrt)
numerator_sub = (oppb) - (sqrt)
twoa = 2 * a
addition_answer = (numerator_add) / (twoa)
subtraction_answer = (numerator_sub) / (twoa)
print(addition_answer)
print(subtraction_answer)
Your solution is fine, let's prove it using sympy:
>>> (x**2+10*x+25).subs(x,-5)
0
As you can see, -5 is one of the roots while 5
>>> (x**2+10*x+25).subs(x,5)
100
is not, now... if you expand your 2 roots [-5,-5] like:
>>> ((x+5)*(x+5)).expand()
x**2 + 10*x + 25
You can see like the result matches.
In fact, you can also confirm the roots are correct displaying the quadratic equation:
I'd strongly recommend you review the concept of The Quadratic Formula and when it's clear just come back to the coding

Quad form program not solving correctly

import cmath
a = float(input("A: "))
b = float(input("B: "))
c = float(input("C: "))
negB = float(b*-1)
sqrtVAR = (b**2-4*a*c)
plus = (negB+cmath.sqrt(sqrtVAR)/2*a)
minus = (negB-cmath.sqrt(sqrtVAR)/2*a)
print(plus)
print(minus)
when i run it negB does not add with the rest of the equation and the answers come out wrong anyway
As pacholik mentions, you've forgotten some parentheses, so your calculation is incorrect.
Also, you are unnecessarily calculating the same square root twice.
The code below adds a function, quad, to test that the found roots are actually zeroes of the equation.
import cmath
a = float(input("A: "))
b = float(input("B: "))
c = float(input("C: "))
def quad(x):
return a*x*x + b*x +c
d = cmath.sqrt(b*b - 4*a*c)
x1 = (-b + d) / (2*a)
x2 = (-b - d) / (2*a)
print(x1, quad(x1))
print(x2, quad(x1))
test
A: 1
B: 2
C: 3
(-1+1.41421356237j) 0j
(-1-1.41421356237j) 0j

Python 3 code is not performing as expected, Giving incorrect numbers

I've recently gotten into Python, and I couldn't come up with any things to make. So i decided i'd port all of my Project Euler stuff over to Python just to have something to do. But basically, the code below is supposed to find the product of a, b, and c, where a + b + c = 1000. (Pythagorean triplet)
from math import sqrt
def solve():
product = 0
for a in range(1, 500):
for b in range(1, 500):
needed = sqrt(a*a + b*b)
if a + b + needed == 1000:
product = a * b * needed
return product
return product
print(solve())
This code produces the correct result, which is 31875000.0. I want it to return an integer, and not a floating point value. I tried doing
needed = round(sqrt(a*a + b*b))
but for some reason, this returns the number 498002, which is not even close to being the same number. I've also tried using Floor from the math library, but that also does the same thing, as well as int(). Is there something that I'm overlooking? Or is this a bug? Or what. I'm using Python 3.5 if that matters.
Because when you round() off, or even do int() to convert the sqrt() result to integer, you are losing precision, like in case of i being 2 and j being 499 , since i is so small , the sqrt of a^2 + b^2 would be something like - 499.0040079999358 - rounding that off would give 499 . And your program would wrongly assume this to be a triplet ,since 499 + 499 + 2 is 1000.
Instead of rounding the result of sqrt you should convert the product to integer before returning. Example -
from math import sqrt
def solve():
product = 0
for a in range(1, 500):
for b in range(1, 500):
needed = sqrt(a*a + b*b)
if a + b + needed == 1000:
product = a * b * needed
return int(product)
return product
print(solve())

Categories