首页 > 编程知识 正文

python中sqrt函数用法Python sqrt 函数,sqrt函数用法python

时间:2023-05-06 07:52:59 阅读:193154 作者:3385

开平方

函数 sqrt() 返回 x 的平方根(x > 0)

语法:

import math

math.sqrt( x )

注意: 此函数不可直接访问,需要导入math模块,然后需要使用math静态对象调用此函数。

参数 x — 数值表达式

返回结果是浮点数。

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

实例1. 请利用filter()过滤出1~100中平方根是整数的数,即结果应该是:

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

import math

def is_sqr(x):

r = int(math.sqrt(x))

return r * r == x

print filter(is_sqr, range(1, 101))

实例2.

def find_next_square(sq):

import math

n = math.sqrt(sq)

if int(sq) == int(n) * int(n): #此处解决了(整数与浮点数的问题)

return (int((n+1)*(n+1)))

else:

return -1

print(find_next_square(4.0))

#输出结果

9

2. 开n次方

利用pow(a, b)函数即可。需要开 a 的 r 次方则pow(a, 1.0/ r )。

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。