Quad form program not solving correctly - python

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

Related

Function using input() for default parameters -- inputs collected but no output printed

I tried making a program to get inputs for the variables in a quadratic equation and print the roots.
import math
def quadratic_solver(a = input("Enter the value of a "), b = input("Enter the value of b "), c = input("Enter the value of c ")):
dis = b * b - 4 * a * c
sqrt_val = math.sqrt(abs(dis))
if dis > 0:
print((-b + sqrt_val)/(2 * a))
print((-b - sqrt_val)/(2 * a))
elif dis == 0:
print(-b / (2 * a))
else:
print(- b / (2 * a), " + i", sqrt_val)
print(- b / (2 * a), " - i", sqrt_val)
Why does the program ask for the input values (as it should) but does not give any output?
When you put input() in the function definition, those will run without you even having to call the function; those are executed regardless, since default values are evaluated when a function is defined, not when it's called. I don't see anywhere where you're calling the function, so I'm assuming you're never actually calling it, thus leading to no print outputs while still getting the input prompts.
To fix the issues, you need to call the function, as well as put the inputs inside of it.
In addition, your a b and c values are being read as strings, but never converted to numbers, which will lead to an error about this if you don't convert them first, so I put in a conversion to float in order to make it work.
import math
def quadratic_solver(a=None, b=None, c=None):
if a is None:
a = float(input("Enter the value of a "))
if b is None:
b = float(input("Enter the value of b "))
if c is None:
c = float(input("Enter the value of c "))
dis = b * b - 4 * a * c
sqrt_val = math.sqrt(abs(dis))
if dis > 0:
print((-b + sqrt_val)/(2 * a))
print((-b - sqrt_val)/(2 * a))
elif dis == 0:
print(-b / (2 * a))
else:
print(- b / (2 * a), " + i", sqrt_val)
print(- b / (2 * a), " - i", sqrt_val)
if __name__ == '__main__':
quadratic_solver()

quadratic formula using 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}")

Quadratic Equation Solver Math Domain Error

I am trying to make a quadratic equation solver, but each time I run it, it displays a math domain error. Can anyone help me fix it? I am sorta new to Python.
import math
def quadratic(a, b, c):
return [((-b + i * math.sqrt(b**2 - 4*a*c)) / (2 * a)) for i in (-1,1)]
a = int(input("What is the value of a? "))
b = int(input("What is the value of b? "))
c = int(input("What is the value of c? "))
print(quadratic(a, b, c))
Your code works in general, but should check if b**4-a*c is positive. That is (probably) why you are getting an error
def quadratic(a, b, c):
D = b**2 - 4*a*c
if D >= 0:
return [((-b + i * math.sqrt(D)) / (2 * a)) for i in (-1, 1)]
else:
return None

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

Python newtons method issues

I have been asking the community alot for help and i appreciate it all
So ive been working on a program that solves newtons method in python but for some reason its not working could someone look over it please? thanks you =)
import sympy
from collections import defaultdict
def main():
dir(sympy)
print ("NEWTONS METHOD")
print ("Write your expression in terms of 'x' ")
e = sympy.sympify(raw_input("input expression here: "))
f = sympy.Symbol('x')
func1 = e
func1d = sympy.diff(e,f) #takes the dirivative of the function
print ("the dir of your function = "), func1d
x = input("number to substitute for x: ")
a = input("how many digits would you like to round to [recomended at least 4]")
func1sub = func1.subs({'x':x}) #substitutes the user given value of x into the equation
func1dsub = func1d.subs({'x':x}) #substitutes the user given value of x into the equation
func1sub = float(func1sub)
func1dsub = float(func1dsub)
func1sub = round(func1sub)
func1dsub = round(func1dsub)
round(func1sub,a)
round(func1dsub,a)
n = x - (func1sub/func1dsub)
x1 = 0
x2 = 0
n = x - (func1sub/func1dsub)
x1 = n
x1 = round(x1)
n = x2 - (func1sub/func1dsub)
x2 = n
x2 = round(x2)
while 0 == 0:
if abs(x1-x2) < .0001:
print x1
break
else:
n = x2 - (func1sub/func1dsub)
x2 = n
if abs(x - n) < .03:
print x
if func1dsub == 0:
print ("ERROR CAN NOT DIVIDE BY 0")
main()
You're getting an infinite loop here:
while 0 == 0:
if abs(x1-x2) < .0001:
print x1
break
else:
n = x2 - (func1sub/func1dsub)
x2 = n
if abs(x - n) < .03:
print x
The part of this loop which matters seems to be:
n = x2 - (func1sub/func1dsub)
x2 = n
And your loop condition is abs(x1-x2) < .0001, so let's rewrite this:
while abs(x1 - x2) >= .0001:
x2 -= (func1sub / func1dsub)
print x1
So maybe x2 -= (func1sub / func1dsub) is pushing x2 the wrong way. I'd add a print statement like this and make sure the values are actually converging:
while abs(x1 - x2) >= .0001:
x2 -= (func1sub / func1dsub)
print (x1, x2)
Also, I'm not that familiar with Newton's method, but in your code func1sub / func1dsub never changes, but shouldn't it change on every iteration?

Categories