勤学教育网合作机构> > 杭州天眼教育欢迎您!

python如何求平方

杭州天眼教育logo
来源:杭州天眼教育

2022-04-15|已帮助:3994

进入 >
打开电脑上的计算器一看,居然没法求平方,是不是就没办法了呢?用python就可以啦,那么python如何求平方呢?一起来了解下吧:
python如何求平方
python如何求平方
1.计算乘方
pow(4,3)
# 结果64
2.计算平方
import numpy
numpy.square(4)
# 结果16
pow(5,2)
#结果25
3.平方根
import numpy
numpy.sqrt(16)
# 结果4.0
numpy.sqrt(16.)
# 结果4.0
pow(25, 0.5)
#结果5.0
pow(25, .5)
#结果5.0
import math
math.sqrt(25)
#结果5.0
math.sqrt(25.0)
#结果5.0
Python中求1到20平方的方法
1.使用列表推导式
>>> [x**2 for x in range(1,21)]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400]
#使用lambda
>>> [(lambda x:x**2)(x) for x in range(1,21)]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400]
#2.使用map函数
>>> def cube(x):
return x**2
>>> list(map(cube,range(1,21)))
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400]
#使用map+lambda
>>> list(map(lambda x:x*x,range(1,21)))
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400]
Python中利用sqrt()求平方的方法
sqrt()方法返回x的平方根(x>0)。
语法
以下是sqrt()方法的语法:
import math
math.sqrt( x )
注意:此函数是无法直接访问的,所以我们需要导入math模块,然后需要用math的静态对象来调用这个函数。
Python中利用sqrt()求平方的方法
参数
? x -- 这是一个数值表达式。
返回值
此方法返回x的平方根,对于x>0。
例子
下面的例子显示了sqrt()方法的使用。
#!/usr/bin/python
import math # This will import math module
print "math.sqrt(100) : ", math.sqrt(100)
print "math.sqrt(7) : ", math.sqrt(7)
print "math.sqrt(math.pi) : ", math.sqrt(math.pi)
当我们运行上面的程序,它会产生以下结果:
math.sqrt(100) : 10.0
math.sqrt(7) : 2.64575131106
math.sqrt(math.pi) : 1.77245385091
python如何求积分
python的numpy库集成了很多的函数。利用其中的函数可以很方便的解决一些数学问题。本篇介绍如何使用python的numpy来求解积分。代码如下:
# -*- coding: utf-8 -*-
import numpy as np
from scipy.integrate import quad,dblquad,nquad
def main():
print quad(lambda x:np.exp(-x),0,np.inf)
'''求积分,np.inf代表正无穷。
结果第一个数值代表运算结果,第二个数值代表误差
'''
print dblquad(lambda t,x:np.exp(-x*t)/t**3,0,np.inf,lambda x:1,lambda x:np.inf)
'''
求二重积分 然后给t,x赋积分区间
lambda是匿名函数
'''
if __name__ == "__main__":
main()
结果如下:
(1.0000000000000002, 5.842607038578007e-11)
(0.3333333333366853, 1.3888461883425516e-08)

以上是杭州天眼教育整理的python如何求平方全部内容。

热门推荐

更多
勤学培训网 python学习网 python如何求平方