简体   繁体   English

二次方程的数学域错误 python

[英]math domain error python for quadratic equation

I'm a complete beginner and for some reason when I try to run the code it says that there's a math domain error.我是一个完全的初学者,出于某种原因,当我尝试运行代码时,它说存在数学域错误。 I don't really understand what the problem is, help would be greatly appreciated:)我真的不明白问题是什么,帮助将不胜感激:)

a = float(input('Rentrer la valeur de a : '))
b = float(input('Rentrer la valuer de b : '))
c = float(input('Rentrer la valuer de c : '))
delta = b**2 - 4*a*c

x1 = ((-b) + sqrt(delta)) / (2*a)
x2 = ((-b) - sqrt(delta)) / (2*a)

console:

Traceback (most recent call last):
  File "main.py", line 31, in <module>
    x1 = ((-b) + sqrt(delta)) / (2*a)
ValueError: math domain error

The sqrt function must take as a parameter a positive number . sqrt function 必须将正数作为参数。 When you enter the number a , b , and c you must make sure that the delta (discriminant) value is positive (see https://en.wikipedia.org/wiki/Discriminant https://www.expii.com/t/the-discriminant-of-a-quadratic-4540 ).当您输入数字abc时,您必须确保增量(判别)值为正(参见https://en.wikipedia.org/wiki/Discriminant https://www.expii.com/t /the-discriminant-of-a-quadratic-4540 )。 If you enter the values a=1, b=3, c=-2 you won't see this error, since in this case the delta value is 17 (a positive number)如果您输入值 a=1、b=3、c=-2,您将不会看到此错误,因为在这种情况下增量值为 17(正数)

If you know what complex numbers are, you can use the sqrt function from the cmath package instead (from cmath import sqrt) and avoid this error, but you would be working with complex numbers.如果您知道什么是复数,则可以使用 cmath package 中的 sqrt function 代替(from cmath import sqrt)并避免此错误,但您将使用复数。

The answer is quite surprisingly easy: you need the math lib:答案非常简单:您需要math库:


from math import sqrt

a = float(input('Rentrer la valeur de a : '))
b = float(input('Rentrer la valuer de b : '))
c = float(input('Rentrer la valuer de c : '))
delta = b**2 - 4*a*c

x1 = ((-b) + sqrt(delta)) / (2*a)
x2 = ((-b) - sqrt(delta)) / (2*a)

print(x1, x2)

"""

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM