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
Related
I wrote a python code to find root of 2*x-4 using bisection method
def func(x):
return 2*x-4
def bisection(a,b):
if (func(a) * func(b) >= 0):
print("You have not assumed right a and b\n")
return
c = a
while ((b-a) >= 0.01):
c = (a+b)/2
if (func(c) == 0.0):
break
if (func(c)*func(a) < 0):
b = c
else:
a = c
print("The value of root is : ","%.0f"%c)
a =-2
b = 4
bisection(a, b)
Now i want that the function input should be given by the user in the form of mx+n where m and n are integers. Can anyone help how can i do that ?
m, n = list(map(int, input("Please enter the value of [m] [n] for f(x) = mx +n: ").split()))
def Input():
a, b = list(map(int, input("Enter values of [a] [b]: ").split()))
if f(a)*f(b)<0:
Bisection(a, b)
else:
print("Oops! The root of function doesn't belong to the above domain\nPlease try to again:")
Input()
def f(x):
return m*x + n
def Bisection(a, b):
c = (a+b)/2
if f(c)*f(b)<0:
Bisection(c, b)
elif f(c)*f(a)<0:
Bisection(c, a)
elif f(c)==0:
print(c)
Input()
See we know that Bisection, Newton-Raphson, or most of all Numerical methods are the iteration processes so better we use function inside of function: f(f(f(f.....) Of course! by checking the conditions.
Here, I have used elif f(c)==0 this is something which we can't use for quadratic/cubic or higher-order polynomials because getting the exact root will not be possible for all the types of equations say like f(x) = mx^2 - n where m, n > 0 However, we can define the iterations to be performed.
By asking like Please enter the number of iterations to be performed:
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()
I have written the following code to find the roots of an equation using the bisection method.
def f(x):
return x**3-5
#computes f(x) intercept with the bisection method
#err - a small floating number that tells you your accuracy
def bisection(low, high, err):
mid = (high+low)/2
while(abs(f(mid)) > err):
print ('low =', low, 'high =', high, 'mid= ', mid)
if f(mid) > 0:
high = mid
elif f(mid) < 0:
low = mid
mid = (high + low)/2
return mid
print (bisection(0, 100, 0.001))
The code executes the method without a problem. However, I would like to find a way to prompt the user to input their own equations to solve rather than it already pre-programmed.
I appreciate any input you have.
Thank you very much for your help!
from sympy import *
eqn=sympify(input('Eqn'))
f=lambda x:eqn.subs({'x':x})
You can prompt the user for coefficients for a polynomial:
print('a x^3 + b x^2 + c x + d')
a = input('>a')
b = input('>b')
c = input('>c')
d = input('>d')
and then you input this into the function:
def f(x, a, b, c, d):
return a*x**3 + b*x**2 + c * x + d
A better way (continuing from #SmartManoj 's answer):
from sympy import *
equation = input('Your equation > ')
eqn=sympify(equation)
f=lambda x:eqn.subs({'x':x})
If you're using python 2, use raw_input('Your equation > ') instead.
There is no need for Sympy, eval is native.
def f(expr, x)
return eval(expr)
for i in range(10):
print f("x * x", i)
I am supposed to write a program that prompts the user for the lengths of three sides of a triangle, determines that the three lengths can form a triangle and if so uses Heron's formula to compute the area to 4 digits of precision.This is what I have so far I don't know where or how to put in the math
import math
def main():
print()
print("Triangle Area Program")
print()
a, b, c = eval(input("Enter three lengths separated by commas: "))
print()
s = (a+b+c) / 2.0
area = sqrt(s*(s-a)*(s-b)*(s-c))
if a > b:
a, b = b, a
if a > c:
a, c = c, a
if b > c:
b, c = c, b
else:
a + b > c
print("A triangle cannot be formed.")
main()
Here's another possible version of your mathy problem:
import math
def heron(a, b, c):
return 0.25 * math.sqrt((a + (b + c)) * (c - (a - b)) * (c + (a - b)) * (a + (b - c)))
if __name__ == "__main__":
print()
print("Triangle Area Program")
print()
print()
try:
description = "Enter three lengths separated by commas: "
sides = sorted(map(float, input(description).split(',')))
if (sides[1] + sides[2]) < sides[0]:
print("A triangle cannot be formed.")
else:
a, b, c = sides
print("Area of triangle {0}-{1}-{2} is {3:.4f}".format(
sides[0], sides[1], sides[2], heron(a, b, c)))
except Exception as e:
print("Check your input!!!")
print("--> Error: {0}".format(e))
Few notes about this version:
It's parsing your floating-point input values and sorting at the same time, that way you can check directly whether a triangle can be formed or not
It's not using the naive heron formula, instead is using another one which is numerically stable
I've decided to give you another version because in the comments you'll find some good advices about yours
Here's a slightly modified version of your program that checks if the inputs are compatible in one compound conditional expression and replaces the use of eval:
import math
def main():
print("\nTriangle Area Program\n")
a, b, c = map(float, input("Enter three lengths separated by commas: ").split(','))
if a + b > c and a + c > b and b + c > a:
s = (a + b + c) / 2.0
area = math.sqrt(s*(s-a)*(s-b)*(s-c))
return round(area, 4) # round area to four decimal places
else:
raise ValueError("The inputs you entered cannot form a triangle")
if __name__ == '__main__':
print(main())
More on avoiding eval when you can Why should exec() and eval() be avoided?
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