-1

In Python

int (1000000000000000000/3)=333333333333333312

But it should be:

int (1000000000000000000/3)=333333333333333333

I am new to python.

James Z
  • 11,838
  • 10
  • 25
  • 41
  • 1
    Your "real" answer is an approximation (i.e. you round the result to the floor with an int cast) and so is the one that Python generates: it's just your approximation is closer. I'm afraid that this comes with the territory (i.e. finite computing of approximation to reals). If you need greater accuracy than the standard resources allow you then you need to use a specialist library in whatever language environment you are using. – adrianmcmenamin Jul 31 '17 at 11:53
  • 2
    @adrianmcmenamin: Your explanation is somewhat misleading, the rounding error is not created by the int cast, but by the floating point division. Python's `int` function is a precise implementation of the "truncate towards zero" operation for floating point numbers, but it doesn't remove rounding errors that were already present in its argument. – Rörd Jul 31 '17 at 12:12
  • I didn't say the rounding error was caused by the cast. I'm just making the point that the OP sought an approximation and unfortunately got a worse one that expected - but every approximation carries the risk of error and arbitrary precision will likely need special libraries. – adrianmcmenamin Jul 31 '17 at 16:29

1 Answers1

2

You need to apply floor division // to get that result in python3 as below:

In [1]: 1000000000000000000//3
Out[1]: 333333333333333333
Gahan
  • 3,616
  • 4
  • 17
  • 38
  • Of course, you don't even need to explicit conversion to an integer with `int` in this case, because the result of a floor division is already an integer. – Rörd Jul 31 '17 at 12:00
  • 1
    @Rörd sorry i forgot to remove it while checking it through python2. thanks for pointing out – Gahan Jul 31 '17 at 12:01
  • Is there any explanation for: int (1000000000000000000/3)=333333333333333312 why it is giving this result? – shashank jaiswal Jul 31 '17 at 12:53
  • @shashankjaiswal there are some link like https://stackoverflow.com/questions/183853/in-python-2-what-is-the-difference-between-and-when-used-for-division or https://stackoverflow.com/questions/21316968/division-in-python-2-7-and-3-3 – Gahan Jul 31 '17 at 13:37