ValueError:数学域错误(用于2年级方程函数) [英] ValueError: Math domain error (for a 2nd grade equation function)

查看:93
本文介绍了ValueError:数学域错误(用于2年级方程函数)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试自己解决问题,但我不能.它的功能是在y = 0时像'ax2 + bx + c = 0'一样求解2年级方程.当我执行它时,它说我存在数学域错误.如果您能帮助我,那就太好了.

I've tried to solve the problem myself but i cant. Its a function in order to solve 2nd grade equations when y=0 like 'ax2+bx+c=0'. when i execute it it says me there is math domain error. if u can help me it will be nice thx.

a=raw_input('put a number for variable a:')    
b=raw_input('put a number for variable b:')    
c=raw_input('put a number for variable c:')

a=float(a)    
b=float(b)    
c=float(c)`

import math


x=(-b+math.sqrt((b**2)-4*a*c))/2*a    
print x`

x=(-b-math.sqrt((b**2)-4*a*c))/2*a`    
print x

PD:im以python开头,因此非常抱歉.

PD:im starting with python so im quite a disaster sorry.

推荐答案

此处的问题是python中的标准math库无法处理复杂的变量.您在那里的sqrt反映了这一点.

The issue here is that the standard math library in python cannot handle complex variables. The sqrt you've got up there reflects this.

如果您想处理一个可能具有复杂变量的函数(例如上述变量),我建议使用cmath

If you want to handle a function that could have complex variables (such as the one above) I would suggest using the cmath library, which has a replacement cmath.sqrt function.

您可以将上面的代码更改为以下代码:

You could change your above code to the following:

from cmath import sqrt

a = raw_input('put a number for variable a:')    
b = raw_input('put a number for variable b:')    
c = raw_input('put a number for variable c:')

a = float(a)    
b = float(b)    
c = float(c)`

x = (-b + sqrt((b**2) - 4 * a * c)) / 2 * a    
print x`

x = (-b - sqrt((b**2) - 4 * a * c)) / 2 * a`    
print x

它应该可以解决您的问题(我还进行了一些编辑,以使代码看起来更像pythonic(请参阅:pep8兼容))

and it should fix your problem (I also made some edits to make the code look a little more pythonic (read: pep8 compliant))

这篇关于ValueError:数学域错误(用于2年级方程函数)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆