亲宝软件园·资讯

展开

Python妙开根号的三种方式

TUSTer_ 人气:17

前言:

大家好啊!又是我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)

三,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

总结

本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注的更多内容!

加载全部内容

相关教程
猜你喜欢
用户评论