Python内容的x**y可以进行指数运算,比如2**3=8。有时候我们需要以参数的方式进行指数计算,这时我们可以使用pow函数,比如:
import
math
for x ,y in [ ( 2 , 3 ) , ( 2.1 , 3.2 ) , ( 1.0 , 5 ) , ( 2.0 , 0 ) ,
( 2 , float ( 'nan' ) ) , ( 9.0 , 0.5 ) , ( 27.0 , 1.0/ 3 ) , ]:
print '{:5.1f} ** {:5.3f}={:6.3f}'. format (x ,y , math. pow (x ,y ) )
for x ,y in [ ( 2 , 3 ) , ( 2.1 , 3.2 ) , ( 1.0 , 5 ) , ( 2.0 , 0 ) ,
( 2 , float ( 'nan' ) ) , ( 9.0 , 0.5 ) , ( 27.0 , 1.0/ 3 ) , ]:
print '{:5.1f} ** {:5.3f}={:6.3f}'. format (x ,y , math. pow (x ,y ) )
其输出结果为:
2.0 ** 3.000= 8.000
2.1 ** 3.200=10.742
1.0 ** 5.000= 1.000
2.0 ** 0.000= 1.000
2.0 ** nan= nan
9.0 ** 0.500= 3.000
27.0 ** 0.333= 3.000
2.1 ** 3.200=10.742
1.0 ** 5.000= 1.000
2.0 ** 0.000= 1.000
2.0 ** nan= nan
9.0 ** 0.500= 3.000
27.0 ** 0.333= 3.000
由于平方非常常用,所有Python中提供了一个sqrt函数用于计算某个数的平方根,注意:不能计算一个负数的平方根:
import
math
print math. sqrt ( 9.0 )
print math. sqrt ( 3 )
try:
print math. sqrt (- 1 )
except ValueError ,err:
print 'Cannot compute sqrt(-1):' ,err
print math. sqrt ( 9.0 )
print math. sqrt ( 3 )
try:
print math. sqrt (- 1 )
except ValueError ,err:
print 'Cannot compute sqrt(-1):' ,err
其输出结果为:
3.0
1.73205080757
Cannot compute sqrt (-1 ): math domain error
1.73205080757
Cannot compute sqrt (-1 ): math domain error
我们还可以求一个数的对数,使用log,比如下面的代码:
import
math
print math. log ( 8 )
print math. log ( 8 , 2 )
print math. log ( 0.5 , 2 )
print math. log ( 8 )
print math. log ( 8 , 2 )
print math. log ( 0.5 , 2 )
其输出结果为:
2.07944154168
3.0
-1.0
3.0
-1.0
Python中提供了一个exp用于进行自然对数e的指数运算:
import
math
x = 2
fmt = '%.20f'
print fmt % ( math. e** 2 )
print fmt % math. pow ( math. e , 2 )
print fmt % math. exp ( 2 )
x = 2
fmt = '%.20f'
print fmt % ( math. e** 2 )
print fmt % math. pow ( math. e , 2 )
print fmt % math. exp ( 2 )
其输出结果为:
7.38905609893064951876
7.38905609893064951876
7.38905609893065040694
本文详细介绍了Python中的数学运算,包括指数运算、平方根计算、对数运算及自然对数e的指数运算等基本数学操作。通过实例展示了如何使用pow、sqrt、log和exp等函数,并解释了这些函数的应用场景。
2515

被折叠的 条评论
为什么被折叠?



