I Do Not Tell the Future

I do not tell the future.. “I Do Not Tell the Future” is published by Jenna Matlin.

Smartphone

独家优惠奖金 100% 高达 1 BTC + 180 免费旋转




The Problem

How to avoid this simple mistake with round() in Python 3

I recently ran into a bug with my Python code that was the result of the last thing I would suspect: rounding. Here’s how to avoid making the same mistake.

Basically, I expected the round() function to operate as rounding usually does, in that half numbers are rounded up to the next whole number. For example, round(4.5) should return 5 and round(5.5) should return 6.

Right?

Surprisingly, that is not how rounding works in Python. Rounding half numbers does not round up, and in fact, it doesn’t always round down either. Instead, it rounds to the nearest even number.

This behavior is shown by the following:

It is worth pointing out that besides the half-number case, round() works as expected, in that it returns the nearest integer. For example, round(4.4) returns 4 and round(4.6) returns 5.

Note: This is only the case with Python 3. round() in Python 2 behaves as you would usually expect.

We can fix this by defining a new rounding function:

We can also take this a little further. The round() function also has another argument called ndigits that specifies how many digits to round to. For example, we can call round(3.14159, 2) and get 3.14 .

However, we run into a similar issue with rounding half values. Consider the following for example:

To fix this, we can use a similar solution, and scale it to the specified number of decimal places with the following:

I hope this helps!

Add a comment

Related posts:

Reflectie interactieontwerp week 6

Begin deze week was het hoorcollege van de gastdocent. Wat ik erg interessant vond om te horen waren de verschillende modellen om prototypes te maken, maar vooral hoe elk model dan ook een losstaand…

Resah dan Gelisah Uang Kuliah

Cukup mahasiswa saja yang gelisah, Mendikbud jangan. Akhir-akhir ini Mendikbud RI, Nadiem Makarim, tak ubahnya seperti buronan dengan kejahatan tingkat tinggi di mata para mahasiswa. Bagaimana tidak…

Como Trabalhar na Hotmart do Zero

Prazer me chamo Douglas Henrique e sou especialista em Marketing Digital , criei este Artigo para explicar a você como dar os primeiros passos na plataforma HOTMART . Para você que está iniciando…