当前位置:首页 » 编程语言 » floattointpython

floattointpython

发布时间: 2023-09-11 04:45:50

python 如何控制输出的小数长度

Python里面小数点长度精度控制方法:

一、要求较小的精度

将精度高的浮点数转换成精度低的浮点数。

1.round()内置方法

这个是使用最多的,刚看了round()的使用解释,也不是很容易懂。round()不是简单的四舍五入的处理方式。

For the built-in types supporting round(), values are rounded to the
closest multiple of 10 to the power minus ndigits; if two multiples are equally
close, rounding is done toward the even choice (so, for example, both round(0.5)
and round(-0.5) are 0, and round(1.5) is 2).

>>> round(2.5)

2

>>> round(1.5)

2

>>> round(2.675)

3

>>> round(2.675, 2)

2.67

round()如果只有一个数作为参数,不指定位数的时候,返回的是一个整数,而且是最靠近的整数(这点上类似四舍五入)。但是当出现.5的时候,两边的距离都一样,round()取靠近的偶数,这就是为什么round(2.5)
=
2。当指定取舍的小数点位数的时候,一般情况也是使用四舍五入的规则,但是碰到.5的这样情况,如果要取舍的位数前的小树是奇数,则直接舍弃,如果偶数这向上取舍。看下面的示例:

>>> round(2.635, 2)

2.63

>>> round(2.645, 2)

2.65

>>> round(2.655, 2)

2.65

>>> round(2.665, 2)

2.67

>>> round(2.675, 2)

2.67

2. 使用格式化

效果和round()是一样的。

>>> a = ("%.2f" % 2.635)

>>> a

'2.63'

>>> a = ("%.2f" % 2.645)

>>> a

'2.65'

>>> a = int(2.5)

>>> a

2

二、要求超过17位的精度分析

python默认的是17位小数的精度,但是这里有一个问题,就是当我们的计算需要使用更高的精度(超过17位小数)的时候该怎么做呢?

1. 使用格式化(不推荐)

>>> a = "%.30f" % (1/3)

>>> a

'0.'

可以显示,但是不准确,后面的数字往往没有意义。

2. 高精度使用decimal模块,配合getcontext

>>> from decimal import *

>>> print(getcontext())

Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999,
capitals=1, clamp=0, flags=[], traps=[InvalidOperation, DivisionByZero,
Overflow])

>>> getcontext().prec = 50

>>> b = Decimal(1)/Decimal(3)

>>> b

Decimal('0.')

>>> c = Decimal(1)/Decimal(17)

>>> c

Decimal('0.')

>>> float(c)

0.058823529411764705

默认的context的精度是28位,可以设置为50位甚至更高,都可以。这样在分析复杂的浮点数的时候,可以有更高的自己可以控制的精度。其实可以留意下context里面的这rounding=ROUND_HALF_EVEN
参数。ROUND_HALF_EVEN, 当half的时候,靠近even.

三、关于小数和取整

既然说到小数,就必然要说到整数。一般取整会用到这些函数:

1. round()

这个不说了,前面已经讲过了。一定要注意它不是简单的四舍五入,而是ROUND_HALF_EVEN的策略。

2. math模块的ceil(x)

取大于或者等于x的最小整数。

3. math模块的floor(x)

去小于或者等于x的最大整数。

>>> from math import ceil, floor

>>> round(2.5)

2

>>> ceil(2.5)

3

>>> floor(2.5)

2

>>> round(2.3)

2

>>> ceil(2.3)

3

>>> floor(2.3)

2

>>>

② python内置函数

python内置函数是什么?一起来看下吧:

python内置函数有:

abs:求数值的绝对值
>>>abs(-2) 2
pmod:返回两个数值的商和余数

>>>pmod(5,2) (2,1) >>pmod(5.5,2) (2.0,1.5)
bool:根据传入的参数的逻辑值创建一个布尔值

>>>bool() #未传入参数 False >>>bool(0) #数值0、空序列等值为False False >>>bool(1) True
all:判断可迭代对象的每个元素是否都为True值
>>>all([1,2]) #列表中每个元素逻辑值均为True,返回True True >>> all(()) #空元组 True >>> all({}) #空字典 True
help:返回对象的帮助信息
>>> help(str)  Help on class str in mole builtins: class str(object) |  str(object='') -> str |  str(bytes_or_buffer[, encoding[, errors]]) -> str |   |  Create a new string object from the given object. If encoding or |  errors is specified, then the 雹清object must expose a data buffer |  that will be decoded using the given encoding and error handler. |  Otherwise, returns the result of object.__str__() (if defined) |  or repr(object). |  encoding defaults to sys.getdefaultencoding(). |  errors defaults to 'strict'. |   |  Methods defined here: |   |  __add__(self, value, /)           Return self+value.
_import_:动态导入模块
index = __import__('index') index.sayHello()
locals:返回当前作用域内的局部变量和其值组成的字典
>>> def f():     print('before define a ')     print(locals()) #作用域内无变量     a = 1     print('after define a')     print(locals()) #作用域内有一个a变量,值为1 >>> f>>> f() before define a  {}  after 磨枝define a {'a': 1}
input:读取用户输入值
>>瞎肆敏> s = input('please input your name:') please input your name:Ain >>> s 'Ain'
open:使用指定的模式和编码打开文件,返回文件读写对象
# t为文本读写,b为二进制读写 >>> a = open('test.txt','rt') >>> a.read() 'some text' >>> a.close()
eval:执行动态表达式求值
>>> eval('1+2+3+4') 10

除了上述举例的函数之外,内置函数按分类还可分为:

1、数学运算(7个)

2、类型转换(24个)

3、序列操作(8个)

4、对象操作(7个)

5、反射操作(8个)

6、变量操作(2个)

7、交互操作(2个)

8、文件操作(1个)

9、编译操作(4个)

10、装饰器(3个)

③ python float函数字符串转换浮点数 保留位数

int函数能够
(1)把符合数学格式的数字型字符串转换成整数
(2)把浮点数转换成整数,但是只是简单的取整,而非四舍五入。

举例:

1 aa = int("124") #Correct
2 print "aa = ", aa #result=124
3 bb = int(123.45) #correct
4 print "bb = ", bb #result=123
5 cc = int("-123.45") #Error,Can't Convert to int
6 print "cc = ",cc
7 dd = int("34a") #Error,Can't Convert to int
8 print "dd = ",dd
9 ee = int("12.3") #Error,Can't Convert to int
10 print ee
11

二、float函数将整数和字符串转换成浮点数。

举例:

1 aa = float("124") #Correct
2 print "aa = ", aa #result = 124.0
3 bb = float("123.45") #Correct
4 print "bb = ", bb #result = 123.45
5 cc = float(-123.6) #Correct
6 print "cc = ",cc #result = -123.6
7 dd = float("-123.34") #Correct
8 print "dd = ",dd #result = -123.34
9 ee = float('123v') #Error,Can't Convert to float
10 print ee

三、str函数将数字转换成字符

举例:

1 aa = str(123.4) #Correct
2 print aa #result = '123.4'
3 bb = str(-124.a) #SyntaxError: invalid syntax
4 print bb
5 cc = str("-123.45") #correct
6 print cc #result = '-123.45'
7 dd = str('ddd') #correct
8 print dd #result = ddd
9 ee = str(-124.3) #correct
10 print ee #result = -124.3

④ 【Python基础】python基本语法规则有哪些

Python基本语法

Python的语法相对比C,C++,Java更加简洁,比较符合人的正常思维。本篇介绍Python的基本语法,通过本篇文章你可以学到以下内容。

掌握Python的基本语法

识别Python中的关键字

Python是一门脚本语言,有以下特点:

面向对象:类

语法块:使用缩进进行标记

注释: #单行注释,"""多行注释""",'''我也是多行注释''

打印与输出:print(), input()

变量: 变量在赋值的时候确定变量的类型

模块:通过import 模块名进行加载模块

Python的标识符

标识符是用户编程时使用的名字,用于给变量、常量、函数、语句块等命名,以建立起名称与使用之间的关系。标识符通常由字母和数字以及其它字符构成。

标识符的命名遵循以下规定:

开头以字母或者下划线_,剩下的字符数字字母或者下划线

Python遵循小驼峰命名法

不是使用Python中的关键字进行命名

代码示例:

num = 10 # 这是一个int类型变量

错误命名示例:

123rate(数字开头)、 mac book pro(含有空格),class(关键字)

Python关键字
以下列表中的关键字不可以当作标识符进行使用。Python语言的关键字只包含小写字母。

⑤ Python如何转换百分数字符串为浮点数

int函数能够
(1)把符合数学格式的数字型字符串转换成整数
(2)把浮点数转换成整数,但是只是简单的取整,而非四舍五入。

举例:

1 aa = int("124") #Correct
2 print "aa = ", aa #result=124
3 bb = int(123.45) #correct
4 print "bb = ", bb #result=123
5 cc = int("-123.45") #Error,Can't Convert to int
6 print "cc = ",cc
7 dd = int("34a") #Error,Can't Convert to int
8 print "dd = ",dd
9 ee = int("12.3") #Error,Can't Convert to int
10 print ee
11

二、float函数将整数和字符串转换成浮点数。

举例:

1 aa = float("124") #Correct
2 print "aa = ", aa #result = 124.0
3 bb = float("123.45") #Correct
4 print "bb = ", bb #result = 123.45
5 cc = float(-123.6) #Correct
6 print "cc = ",cc #result = -123.6
7 dd = float("-123.34") #Correct
8 print "dd = ",dd #result = -123.34
9 ee = float('123v') #Error,Can't Convert to float
10 print ee

三、str函数将数字转换成字符

举例:

1 aa = str(123.4) #Correct
2 print aa #result = '123.4'
3 bb = str(-124.a) #SyntaxError: invalid syntax
4 print bb
5 cc = str("-123.45") #correct
6 print cc #result = '-123.45'
7 dd = str('ddd') #correct
8 print dd #result = ddd
9 ee = str(-124.3) #correct
10 print ee #result = -124.3

⑥ 怎么将python时间段(Timedelta)转化为int或float数值形式! 急。

1、打开visio studio 2015,在文件中打开新建项目,新建一个Python应用程序,并修改程序的名称为int2date。

⑦ python中如何把string 转换成int

用数字字符串初始化int类,就可以将整数字符串(str)转换成整数(int):

In [1]: int(‘1234’)

Out[1]: 1234

相反用整数初始化str类,就可以将整数(int)转换为对应的字符串(str):

In [2]: str(1234)

Out[2]: ‘1234’

如果字符串是浮点数,可以用字符串初始化float类,把浮点数字符串(str)转换成浮点数(float):

In [3]: float(‘12.34’)

Out[3]: 12.34

(7)floattointpython扩展阅读:

Python (英国发音:/ˈpaɪθən/ 美国发音:/ˈpaɪθɑːn/), 是一种面向对象的解释型计算机程序设计语言,由荷兰人Guido van Rossum于1989年发明,第一个公开发行版发行于1991年。

Python是纯粹的自由软件,源代码和解释器CPython遵循 GPL(GNUGeneral Public License)许可。Python语法简洁清晰,特色之一是强制用空白符(white space)作为语句缩进。

Python具有丰富和强大的库。它常被昵称为胶水语言,能够把用其他语言制作的各种模块(尤其是C/C++)很轻松地联结在一起。常见的一种应用情形是,使用Python快速生成程序的原型(有时甚至是程序的最终界面),然后对其中有特别要求的部分,用更合适的语言改写,比如3D游戏中的图形渲染模块,性能要求特别高,就可以用C/C++重写,而后封装为Python可以调用的扩展类库。需要注意的是在您使用扩展类库时可能需要考虑平台问题,某些可能不提供跨平台的实现。

7月20日,IEEE发布2017年编程语言排行榜:Python高居首位 。

2018年3月,该语言作者在邮件列表上宣布 Python 2.7将于2020年1月1日终止支持。用户如果想要在这个日期之后继续得到与Python 2.7有关的支持,则需要付费给商业供应商。

热点内容
滑板鞋脚本视频 发布:2025-02-02 09:48:54 浏览:432
群晖怎么玩安卓模拟器 发布:2025-02-02 09:45:23 浏览:557
三星安卓12彩蛋怎么玩 发布:2025-02-02 09:44:39 浏览:743
电脑显示连接服务器错误 发布:2025-02-02 09:24:10 浏览:537
瑞芯微开发板编译 发布:2025-02-02 09:22:54 浏览:146
linux虚拟机用gcc编译时显示错误 发布:2025-02-02 09:14:01 浏览:235
java驼峰 发布:2025-02-02 09:13:26 浏览:651
魔兽脚本怎么用 发布:2025-02-02 09:10:28 浏览:538
linuxadobe 发布:2025-02-02 09:09:43 浏览:212
sql2000数据库连接 发布:2025-02-02 09:09:43 浏览:726