I am trying to reproduce some Visual Basic code in python. I have a function which produces a fraction (double) and converts it to an integer as follows:
Dim random_int As Integer
Dim rounded_int As Integer
random_int = CInt(Math.Ceiling(Rnd() * n)) + 1
rounded_int = CInt(random_int/2)
CInt()
rounds double values to the nearest integer. However when the value is 0.5, this appears to be random; sometimes up, sometimes down. This makes the code difficult to test. In python(2.7), the number is always rounded in the same direction.
I could add or subtract a small number to the result (e.g. 0.1) but the original code should not changed.
Is this behaviour normal or can I control it in some way?
CInt
in VBA uses Banker's Rounding, also called 'round half to even'. This explains the 'random' behavior. Some examples are:
2.5 -> 2
3.5 -> 4
You cannot customize the behavior using CInt
. Historically, rounding method implementations are inconsistent among Microsoft's various technologies, this KB article illustrates this and provides code samples for various other common forms of rounding.
Another addition: due to floating point technical limitations, 1.5
might be represented as 1.4999999
internally, causing even further confusion. This article tries to explain why this happens and how to solve it.
Edit: I assumed Visual Basic for Applications because of the vba
tag, if you are using Visual Basic .NET you can invoke Math.Round
with a MidpointRounding
overload.