Python 数学模块运算符的优先级不正确?
Python Math Module Operators Precedence Incorrect?
我是 python 编程的新手,搜索了这个问题,以为有解释,但找不到。
为什么这样:
math.log(0.05/(2*0.000001),10)
#output 4.3979400086720375
与此不同:
math.log(0.05/2*0.000001,10)
#output -7.602059991327962
不是运算符的优先级
*
/
and it should give the same answer ?
抱歉,如果我遗漏了什么。
感谢您的帮助!
所以编译器执行的操作就像常规数学一样。这些括号为操作添加了优先级。
因此,编译器在这些情况下要做的第一件事是首先计算括号之间的内容,因此对于第一行,它将以这种方式计算:
math.log(0.05/(2*0.000001), 10) ==> math.log(0.05/(0.000002) , 10) ==> math.log(25000, 10) ==> 4.3979400086720375
对于第二个,它将是第一个运算,因为乘法和除法具有相同的优先级顺序。
math.log(0.05/2 * 0.000001,10) ==> math.log(0.1*0.000001, 10) = => math.log(0.0000001, 10) ==> 7.602059991327962
我用粗体标出了每一步中将要发生的操作。
math.log(0.05/(2*0.000001),10)
这有输出
4.3979400086720375
因为你在multiplied2*0.000001
中用了()这个。因此,根据简化的基本数学规则,即 BODMAS
Bracket of division multiplication addition subtraction
代码先乘括号()
部分再除法
在第二个 math.log(0.05/2*0.000001,10)
中它们没有使用 ()
所以它首先进行除法运算然后乘以 0.000001
我是 python 编程的新手,搜索了这个问题,以为有解释,但找不到。
为什么这样:
math.log(0.05/(2*0.000001),10)
#output 4.3979400086720375
与此不同:
math.log(0.05/2*0.000001,10)
#output -7.602059991327962
不是运算符的优先级
*
/
and it should give the same answer ?
抱歉,如果我遗漏了什么。
感谢您的帮助!
所以编译器执行的操作就像常规数学一样。这些括号为操作添加了优先级。 因此,编译器在这些情况下要做的第一件事是首先计算括号之间的内容,因此对于第一行,它将以这种方式计算:
math.log(0.05/(2*0.000001), 10) ==> math.log(0.05/(0.000002) , 10) ==> math.log(25000, 10) ==> 4.3979400086720375
对于第二个,它将是第一个运算,因为乘法和除法具有相同的优先级顺序。 math.log(0.05/2 * 0.000001,10) ==> math.log(0.1*0.000001, 10) = => math.log(0.0000001, 10) ==> 7.602059991327962
我用粗体标出了每一步中将要发生的操作。
math.log(0.05/(2*0.000001),10)
这有输出
4.3979400086720375
因为你在multiplied2*0.000001
中用了()这个。因此,根据简化的基本数学规则,即 BODMAS
Bracket of division multiplication addition subtraction
代码先乘括号()
部分再除法
在第二个 math.log(0.05/2*0.000001,10)
中它们没有使用 ()
所以它首先进行除法运算然后乘以 0.000001