一篇文章带你了解python标准库--math模块
作者:wakeyo_J 时间:2021-02-22 07:35:12
python语言的一大优势:为科学计算提供了大量的支持功能,math模块提供了很多数学计算函数。
math模块定义了一些数学模块,这个模块属于编译系统自带,因此它可以被无条件调用,需要注意的是,这些函数无法应用于复数。
1. math模块中的常用函数
2. 案例
2.1 浮点数求整
1.用trunc(x)取整,x为浮点数
>>> import math
>>> math.trunc(8.9)
8
>>>
注意,trunc(8.9)返回的值是整数8,而8.9//1返回的是浮点型8.0,可以通过type()函数来验证
2.用math.ceil(x)取大整数,x为浮点数
>>> price=8.65
>>> math.ceil(price)
9
>>>
3.用round(x)四舍五入,x为浮点数
round(x)不是math模块里的函数,而是默认内置函数,但是其可以对浮点数进行四舍五入。
>>> round(8.5)
8
>>> round(3.4)
3
>>>
2.2 对元组里的每个元素求和
>>> t_nums=(4,5,6)
>>> math.fsum(t_nums) #求集合里的元素的和
15.0
>>>
fsum(x)函数与内置函数sum(x)作用类似,唯一区别:前者一律返回浮点数,后者整型元素返回整型和,浮点数元素返回浮点数和。
>>> sum(t_nums)
15
>>> t1=(1.2,2.2,3.1)
>>> sum(t1)
6.5
>>>
2.3 求数的绝对值
>>> height=-5
>>> math.fabs(height) #fabs求绝对值
5.0
>>> abs(height)#内置函数abs求绝对值
5
>>>
若x是浮点数,则abs返回浮点数值。
来源:https://blog.csdn.net/m0_55697123/article/details/119393585
标签:python,math模块
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Ubuntu配置Pytorch on Graph (PoG)环境过程图解
2022-01-13 02:05:12
![](https://img.aspxhome.com/file/2023/6/108056_0s.png)
慢慢的网页
2009-11-12 12:53:00
![](https://img.aspxhome.com/file/UploadPic/200911/12/manmanwangye-95s.jpg)
Python的 元组(Tuple)详解
2021-09-07 13:55:18
![](https://img.aspxhome.com/file/2023/4/120334_0s.png)
Laravel操作redis和缓存操作详解
2023-05-25 02:19:29
跟老齐学Python之总结参数的传递
2021-12-16 18:17:24
在ASP中使用SQL语句之5:开始执行
2007-08-11 12:36:00
ASP实现下载系统防盗链方法
2008-02-01 14:05:00
win10系统下python3安装及pip换源和使用教程
2023-07-10 19:48:40
![](https://img.aspxhome.com/file/2023/0/121040_0s.jpg)
《JavaScript语言精粹》
2009-04-03 11:27:00
图标设计常犯的10种错误
2008-03-06 13:40:00
![](https://img.aspxhome.com/file/UploadPic/20083/6/200836134649762s.jpg)
基于python,Matplotlib绘制函数的等高线与三维图像
2021-09-06 08:51:33
![](https://img.aspxhome.com/file/2023/5/110425_0s.png)
Javascript将数值转换为金额格式(分隔千分位和自动增加小数点)
2023-08-18 10:31:11
Tensorflow中使用cpu和gpu有什么区别
2021-10-15 15:48:45
![](https://img.aspxhome.com/file/2023/9/82769_0s.png)
asp如何对文件进行操作?
2009-11-20 18:31:00
![](https://img.aspxhome.com/file/UploadPic/200911/20/20091120184513823s.gif)
Apache2 httpd.conf 中文版
2023-10-28 04:19:38
巧用Dreamweaver MX共享Execl XP文件
2009-07-14 21:56:00
python中三种输出格式总结(%,format,f-string)
2022-06-11 16:34:40
![](https://img.aspxhome.com/file/2023/6/75356_0s.png)
Python数据可视化Pyecharts库的使用教程
2023-01-24 23:17:34
![](https://img.aspxhome.com/file/2023/0/101320_0s.png)
CentOS系统中PHP和MySQL的升级方法
2023-11-20 21:04:19
ASP幻灯片
2009-09-04 18:05:00