带你了解Python妙开根号的三种⽅式
⽬录
前⾔:
⼀,math库
⼆,cmath库
三,pow()函数
python不同开根号速度对⽐
总结
前⾔:
⼤家好啊!⼜是我TUSTer_!  python⾥有⾃带的库math,cmath,和函数pow来开根号。下边让我带你了解他们吧!记得⼀键三连!
⼀,math库
使⽤math库⾥的sqr()函数,在math库⾥边有很多数学函数,如三⾓函数sin(),pi-π等等:
import math
print(math.sqr(4))
输出结果:2Epsilon = 10e-16
def fab_h(x):
'''
求实数的绝对值
:param x: R
'''
if x >= 0:
return x
else:
return x * -1
def sqrt_h(x, n=2.0):
'''
n倍根号下x
⽜顿迭代法
'''
val = x
last = 0.0
if n == 2.0:
while (fab_h(val - last) > Epsilon):
last = val
val = (val + x / val) / 2
return val
while (fab_h(val - last) > Epsilon):
last = val
val = ((n-1)*val + x / val**(n-1)) / n
return val
⼆,cmath库
cmath多⽤于复数,负数的开平⽅。
# importing cmath library
import cmath
# using cmath.sqrt() method
gfg = cmath.sqrt(3)
print(gfg)
输出:
(1.7320508075688772+0j)numpy教程 pdf
三,pow()函数
pow(x,y)的意思是返回x的y次⽅,如pow(x,2)就是返回x的平⽅,就是x^2,
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import math  # 导⼊ math 模块
print "math.pow(100, 2) : ", math.pow(100, 2)
# 使⽤内置,查看输出结果区别
print "pow(100, 2) : ", pow(100, 2)
print "math.pow(100, -2) : ", math.pow(100, -2)
print "math.pow(2, 4) : ", math.pow(2, 4)
输出:
math.pow(100, 2) :  10000.0
pow(100, 2) :  10000
math.pow(100, -2) :  0.0001
math.pow(2, 4) :  16.0
math.pow(3, 0) :  1.0
python不同开根号速度对⽐
import time
import math
import numpy as np
def timeit1():
s = time.time()
for i in range(750000):
z=i**.5
print ("Took %f seconds" % (time.time() - s))
def timeit2(arg=math.sqrt):
s = time.time()
for i in range(750000):
z=arg(i)
print ("Took %f seconds" % (time.time() - s))
def timeit3(arg=np.sqrt):
s = time.time()
for i in range(750000):
z=arg(i)
print ("Took %f seconds" % (time.time() - s))
def timeit4():
s = time.time()
for i in range(750000):
z=math.pow(i,.5)
print ("Took %f seconds" % (time.time() - s))
timeit1()
timeit2()
timeit3()
timeit4()
Took 0.152364 seconds
Took 0.061580 seconds
Took 1.016529 seconds
Took 0.215403 seconds
总结
本篇⽂章就到这⾥了,希望能够给你带来帮助,也希望您能够多多关注的更多内容!

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。