Home > Back-end >  Why does my round() function fails to calculate correct values for some inputs in Python?
Why does my round() function fails to calculate correct values for some inputs in Python?

Time:01-14

I am trying to get a round value after division between two values.For example, for inputs dividend=10 and divisor =3 , my expected output is 3 but it's saying 3.0 and for inputs p = 7 and t = -3 it's expected out -2 but it's showing -3.0. When I try to run this code in Pycharm I get intended results but when I run this in Leetcode compiler I get following error. Can I optimise this solution? Below is my code

p = 7
t = -3
print(round(p / t))

dividend = 10
divisor = 3
print(round(dividend / divisor))

I have changed my leetcode Python version to Python 3 and now these inputs get passed but only one input test case is failing. For inputs dividend = -2147483648 and divisor = -1, expected output is 2147483647 but I get 2147483648

CodePudding user response:

What you describe is a notable difference between python2 and python3, which can almost be considered to be different programming languages.

Python3

In python3, / always returns a float, and round always returns an int.

print(2 / 1)
# 2.0

print(round(3.5))
# 4

If you want to get integer (Euclidean) division in python3, then do not use / nor round, but use // instead:

print(9 / 2)
# 2.25

print(9 // 2)
# 2

Python2

In python2, / returns either an int or a float depending on whether you're dividing ints or floats; and round always returns a float.

print (8 / 4)
# 2
print (9 / 4)
# 2

print (8.0 / 4.0)
# 2.0
print (9.0 / 4.0)
# 2.25

print (round(3))
# 3.0

Identifying the python version

See this related question: Which version of python do I have installed?

In the console you can type: python -v or python --version.

Inside a python interpreter, you can type:

import sys

print(sys.version)

There is also this fun "hack" to exploit the difference in behaviour of / to print "2" in python2 and "3.0" in python3:

print( (3/2) * 2 )

#python3:  3.0
#python2:  2

CodePudding user response:

The round builtin method in Python2 returns a floating point value

Return the floating point value number rounded to ndigits digits after the decimal point. If ndigits is omitted, it defaults to zero. The result is a floating point number. Values are rounded to the closest multiple of 10 to the power minus ndigits; if two multiples are equally close, rounding is done away from 0 (so, for example, round(0.5) is 1.0 and round(-0.5) is -1.0).

If you want to get an integer you need to do two things:

  1. Check if the two numbers have different signs
  2. If they do, you add 1 to the res variable.
class Solution(object):

    def divide_integer(self,dividend,divisor):

        res = dividend//divisor
        if (dividend ^ divisor < 0):
            res  = 1
        return int(res)

This basically compares the sign-bit and Xors them, if they are different, then the sign bit of the new number will be one and thus the number is negative (that is the ... < 0 part of the if statement)

CodePudding user response:

The round() function in Python uses "round half to even" or "banker's rounding" strategy, which can cause some unexpected results when the decimal to be rounded is exactly halfway between two possible rounded values.

For example, if you use round(2.5), it will round to 2 because 2 is the nearest even number. Similarly, round(3.5) will round to 4. This can cause issues if you are expecting the output to always round up or down.

Another possible reason is that the number you are trying to round is not a decimal but a float, and due to the way computers represent decimal numbers with floating-point arithmetic, it can cause errors in the representation of the number itself.

You can try using the decimal module from Python's standard library, which provides a Decimal class for decimal arithmetic with arbitrary precision. This module can provide more accurate results for financial and monetary calculations.

CodePudding user response:

that is why python is a dynamically typed language. if the operation is division then python considers the result in float

so to get what you want you should first round it and return its integer

    int(round(res)) # return 3 only try it
  • Related