首页 > 编程语言 > 基于python不同开根号的速度对比分析
2021
03-11

基于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

补充:Python笔记-开根号的几种方式

前言

使用Python中的自带库math、自带函数pow和自带库cmath来对数字进行开根号运算

方法一

使用:math.sqrt(数字)

import math
n = int(input('数字:'))
x = math.sqrt(n)
print(x)
print(type(x)) #开根号后的类型为float

方法二

使用:pow(数字,次方)

n = int(input('数字:'))
x = pow(n,0.5)
print(x)
print(type(x)) #开根号后的类型为float

方法三

使用:cmath.sqrt(数字)

该方法多用于复数、负数的开方运算

import cmath
n = int(input('数字: '))
x = cmath.sqrt(n)
print(x)
print(type(x)) #类型为complex

以上为个人经验,希望能给大家一个参考,也希望大家多多支持自学编程网。如有错误或未考虑完全的地方,望不吝赐教。

编程技巧