Python 3 gives wrong output when dividing two large numbers?

后端 未结 3 2147
情书的邮戳
情书的邮戳 2020-12-02 01:55
a = 15511210043330985984000000  # (25!)
b = 479001600                   # (12!)
c = 6227020800                  # (13!)

On dividing ans = int

相关标签:
3条回答
  • 2020-12-02 02:35

    In Python 3.x / means floating point division and can give small rounding errors. Use // for integer division.

    ans = a // (b*c)
    
    0 讨论(0)
  • 2020-12-02 02:36

    Try using integer division instead of float division.

    >>> 15511210043330985984000000 / (479001600 * 6227020800)
    5200299.999999999
    >>> 15511210043330985984000000 // (479001600 * 6227020800)
    5200300
    
    0 讨论(0)
  • 2020-12-02 02:49

    Your problem (not using integer arithmetic) has been swept under your carpet for you by Python 3.2:

    Python 3.2 (r32:88445, Feb 20 2011, 21:29:02) [MSC v.1500 32 bit (Intel)] on win32
    Type "help", "copyright", "credits" or "license" for more information.
    >>> 15511210043330985984000000 / (479001600 * 6227020800)
    5200300.0
    >>> repr(15511210043330985984000000 / (479001600 * 6227020800))
    '5200300.0'
    >>> int(15511210043330985984000000 / (479001600 * 6227020800))
    5200300
    
    Python 3.1.3 (r313:86834, Nov 27 2010, 18:30:53) [MSC v.1500 32 bit (Intel)] on win32
    Type "help", "copyright", "credits" or "license" for more information.
    >>> 15511210043330985984000000 / (479001600 * 6227020800)
    5200299.999999999
    >>> repr(15511210043330985984000000 / (479001600 * 6227020800))
    '5200299.999999999'
    >>> int(15511210043330985984000000 / (479001600 * 6227020800))
    5200299
    

    I'm puzzled: presumably you used int() because you realised that it was producing a float answer. Why did you not take the (obvious?) next step of rounding it, e.g.

    [3.1.3]
    >>> int(round(15511210043330985984000000 / (479001600 * 6227020800)))
    5200300
    

    ?

    0 讨论(0)
提交回复
热议问题