标准库中的math,标准库中名为math的模块
先用import函数引入math
[code]import(math)
因为math不是内置函数,所以需要引入
[code]dir(math)
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'comb', 'copysign', 'cos', 'cosh', 'degrees', 'dist', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'isqrt', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'perm', 'pi', 'pow', 'prod', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']
使用dir(math)就能看到math模块里面所有的函数。
怎么使用这些函数
[code]math.pi
3.141592653589793
这样就调用了math模块里面的pi属性
[code]math.pow(2,3)
8.0
表示2的3次方,pow是计算指数的。
[code]>>> 2 ** 3
8
>>> 2 * 3
6
两个 * 表示指数运算,一个 * 表示乘法。
[code] import decimal
>>> a = decimal.Decimal('0.1')
>>> b = decimal.Decimal('0.2')
>>> a
Decimal('0.1')
>>> b
Decimal('0.2')
>>> a + b
Decimal('0.3')
这样得到的就是0.1+0.3的精确值
有关数字预算中的溢出问题
[code]2**1000
10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376
在python计算中,不管多大的整数,计算都不会出现溢出问题,但是对于浮点数就会出问题
[code]2 ** 10000 * 0.1
Traceback (most recent call last):
File "", line 1, in
OverflowError: int too large to convert to float
记住:程序不是在交互模式里面,而是把程序写到一个文件,执行一个文件即可。
建议使用微软的Visual Studio Code编辑器用来编辑程序
[code]1 #coding:utf -8
2 '''
3 my first porgrame.
4 filename:force.py
5 '''
6
7 import math
8 f1 = 20
9 f2 = 10
10 alpha = math.pi / 3
11
12 x_force = f1 + f2 * math.sin(alpha)
13 y_force = f2 * math.cos(alpha)
14
15 force = math.sqrt(x_force * x_force + y_force ** 2)
16
17 print('The result is:', round(force, 2), 'N')
第2行和第3行是单引号或双引号,2-5行之间为文本,即对我们这个文件的描述,这是给人看的,电脑不会去看它。
7- 17行才是这个程序的主体,这个程序是想做:已知 f1、f2两力,两力之间的夹角是 pi / 3(alpha代表它们的夹角), 我想计算这两力的合力。
12 行代表 x 轴上的分力 = f1 + f2 * 夹角的正弦值,即math.sin(alpha)
13行代表 y 轴上的分力 = f2 * 夹角的余弦函数,即math.cos(alpha)
15行代表:把这两力的平方和开方,即这两力的合力大小。
17行:调用了python的内置函数,把计算的数值打印出来,打印同时,利用round进行四舍五入。记得要保存
怎么运行这个写好的程序,可以使用VScode里的Debugging,运行python文件,这是一种调试方式,还有一种调试方式。
进入到保存这个文件的目录,然后……
或者在termimal里面进入:python 文件名 即 python Yangmin Gogogo
本文介绍了Python标准库math模块的使用方法,包括pi常量、指数运算、浮点数溢出问题以及如何通过导入decimal模块处理精度问题。重点讲解了如何调用math模块的函数并应用于力的合成实例中。

被折叠的 条评论
为什么被折叠?



