Python 官方文档:入门教程 => 点击学习
目录前言:一,math库二,cmath库三,pow()函数python不同开根号速度对比总结前言: 大家好啊!又是我TUSTer_! Python里有自带的库math,c
大家好啊!又是我TUSTer_! Python里有自带的库math,cmath,和函数pow来开根号。下边让我带你了解他们吧!记得一键三连!
使用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多用于复数,负数的开平方。
# importing cmath library
import cmath
# using cmath.sqrt() method
gfg = cmath.sqrt(3)
print(gfg)
输出:
(1.7320508075688772+0j)
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
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
本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注编程网的更多内容!
--结束END--
本文标题: 带你了解Python妙开根号的三种方式
本文链接: https://lsjlt.com/news/162789.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0