程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

What are the hidden holes in Python? On the rounding of round function in Python

編輯:Python

After looking around, Gao Zan replied , Nobody even mentioned this .

Everybody knows ,round() It is used for rounding .

however , There are special circumstances :

Have you found any problems ?

  • 7.55 Keep one decimal place , Rounding , Should have 7.6, But I got 7.5

  • 1.315 Keep two decimal places , Rounding , Should the 1.32, But I got 1.31

because ,Python It does not follow rounding , It is “ Round to the nearest pair

Python Official documents :

round Introduce : Built in functions — Python 3.10.5 file

The controversy and limitation of floating point arithmetic :15. Floating point arithmetic : Disputes and restrictions - Python 3.10.5 file

So , I wrote a special function , Fix this problem ( If it counts as a problem ):

def new_round(v_value, ndigits=1):
"""
Repair python The question of rounding
:param ndigits: Keep a few decimal places
:param v_value: Enter the value
:return: Output value
"""
f = int(v_value) % 10
if f <= 4:
v_value = (int(v_value) // 10) / 10
else:
v_value = (int(v_value) // 10 + 1) / 10
print(v_value)
return v_value

Whether it counts or not Python Of bug, But you must know this .

Don't let your program , Because of it , Calculate the wrong result , He didn't know it !

By then , If not python Of bug, It's also your program bug 了 !!

Python Is there any unknown pit ? - You know | Horse brother python say


I'm brother ma , The whole network has tens of thousands of fans , Welcome to share python technology .

Search by platform “ Horse brother python say ”: You know 、 Bili, Bili 、 The little red book 、 Sina weibo .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved