Recent Changes - Search:

Oktatás

* Programozás 1
  + feladatsor
  + GitHub oldal

* Szkriptnyelvek
  + feladatsor
  + quick link

Teaching

* Programming 1 (BI)
  ◇ exercises
  ◇ quick link

teaching assets


Félévek

* 2025/26/2
* archívum


Linkek

* kalendárium
   - munkaszüneti napok '20
* tételsorok
* jegyzetek
* szakdolgozat / PhD
* ösztöndíjak
* certificates
* C lang.
* C++
* C#
* Clojure
* D lang.
* Java
* Nim
* Nim2
* Scala


[ edit | logout ]
[ sandbox | passwd ]

rounding

round()
print(round(1.5))         # 2 , correct

print(round(3.5))         # 4 , correct

print(round(2.5))         # 2 , wat?

print(round(3.14159))     # 3
print(round(3.14159, 2))  # 3.14
print(round(3.14159, 3))  # 3.142
import std/math

echo round(1.5)         # 2.0 (float)

echo round(3.5)         # 4.0

echo round(2.5)         # 3.0 (!)

echo round(3.14159)     # 3.0
echo round(3.14159, 2)  # 3.14
echo round(3.14159, 3)  # 3.142

Python uses the so-called banker's rounding: when a number is exactly halfway between two integers (i.e. the end is .5), then the number is rounded to the nearest even number. Otherwise, rounding happens the traditional way.

Nim uses the traditional rounding, as we learned it in the primary school.

Another difference: when round() is called with just one argument, Python returns an int while Nim alwasy returns a float (whose end is .0 when called with just one argument). If you want an int, apply the int() function on the result:

echo int(round(1.5))  # 2 (int)

What is banker's rounding good for?

I asked an LLM and it gave me the following acceptable answer:

"The purpose of banker's rounding (also known as "round half to even") is to avoid systematic bias.

With traditional rounding (always rounding 0.5 up), if you round many numbers, the results are systematically biased upward — because numbers exactly halfway are always rounded up. With large datasets this accumulates and causes a significant error.

With banker's rounding, halfway numbers are rounded to the nearest even integer:

  • 0.5 → 0 (down, because 0 is even)
  • 1.5 → 2 (up, because 2 is even)
  • 2.5 → 2 (down, because 2 is even)
  • 3.5 → 4 (up, because 4 is even)

This way the roundings up and down statistically cancel each other out, and with large datasets the sum/average remains much more accurate.

It is especially important in financial calculations, which is where the name comes from — if a bank rounds millions of transactions per day, with the traditional method it would systematically account for more money than it should." (Claude AI)

Cloud City

  

Blogjaim, hobbi projektjeim

* The Ubuntu Incident
* Python Adventures
* @GitHub
* heroku
* extra
* haladó Python
* YouTube listák


Debrecen | la France


[ edit ]

Edit - History - Print *** Report - Recent Changes - Search
Page last modified on 2026 April 05, 13:36