0

I'm taking a large integer and dividing it by 5. answer provided by that operation is correct. But when I'm using floor operator then it rounds off it's digit at units place. Rest all digits are same in both cases. Can someone tell what is happening here? Code:

  1 import sys
  2 
  3 def gcd(a, b):
  4     
  5     if b > a:
  6         a, b = b, a
  7 
  8     if b > 0:
  9         return (gcd(a%b, b))
 10     
 11     return a
 12 
 13 def lcm(a, b):
 14     return (a*(b//gcd(a, b)))    #floor operator
 15     
 16 def lcm2(a, b):
 17     return (a*(b/gcd(a, b)))    #division operator
 18 
 19 a, b = 226553150, 1023473145
 20 print (int(lcm(a, b)))
 21 print (int(lcm2(a, b)))

user@ubuntu:~/py$ python3 findlcm.py
46374212988031350
46374212988031352
  • Cannot reproduce: https://repl.it/@replitcode/Test1 – internet_user Jul 01 '18 at 18:01
  • 2
    I can confirm, it reproduces on mine too. – Bharel Jul 01 '18 at 18:02
  • What python version? – internet_user Jul 01 '18 at 18:02
  • Newest - version 3.7.0 – Bharel Jul 01 '18 at 18:03
  • What makes you think the first result is "correct"? *That's* the one with the rounding error. – user2357112 Jul 01 '18 at 18:03
  • `((226553150*1023473145)/5)/10` returns a natural number, multiply it by 10 and it should be modulo 0. – Bharel Jul 01 '18 at 18:04
  • 1
    One, this is following Python 3 rules, not Python 2 (unless you're using `from __future__ import division` and not telling us). In any event, the main issue you're encountering is that using `/ 5` means the operands are converted to `float`, and your numerator is 58 bits of data. Python's `float` is based on C's `double`, which is typically IEE-754 binary64 floating point; binary64 floating point only has 52-53 bits worth of precision, so converting a 58 bit number to `float` is likely to lose precision. – ShadowRanger Jul 01 '18 at 18:05
  • I found a funnier one - `(((226553150*1023473145)/5)//10 * 10) % 10` – Bharel Jul 01 '18 at 18:07

0 Answers0