python 3 long ints and multiplication

后端 未结 2 1197
醉话见心
醉话见心 2021-01-19 03:36

I\'m trying to execute next code int((226553150 * 1023473145) / 5) and python3 gives me an answer 46374212988031352. But ruby and swift give me an

相关标签:
2条回答
  • 2021-01-19 04:05

    You are missing that Python's division (from Python 3 on) is by default a float division, so you have reduced precision in that. Force the integer division by using // instead of / and you will get the same result.

    0 讨论(0)
  • 2021-01-19 04:16

    a / b is a floating-point division in Python 3. In order to perform integer division you should use // operator:

    In [3]: (226553150 * 1023473145) // 5
    Out[3]: 46374212988031350
    

    Floating point division precision limited to the mantissa size:

    In [19]: (226553150 * 1023473145) / 5
    Out[19]: 4.637421298803135e+16
    

    As you can see, Python correctly represents all digits but the last. You could also made some interesting tricks with it:

    In [20]: int((226553150 * 1023473145) / 5)
    Out[20]: 46374212988031352
    
    In [21]: int((226553150 * 1023473145) / 5 - 1)
    Out[21]: 46374212988031352
    
    In [22]: int((226553150 * 1023473145) / 5 + 1)
    Out[22]: 46374212988031352
    
    In [23]: int((226553150 * 1023473145) / 5 - 2)
    Out[23]: 46374212988031352
    
    In [24]: int((226553150 * 1023473145) / 5 - 3)
    Out[24]: 46374212988031352
    
    In [25]: int((226553150 * 1023473145) / 5 - 4)
    Out[25]: 46374212988031344
    
    In [26]: int((226553150 * 1023473145) / 5 + 4)
    Out[26]: 46374212988031360
    
    In [27]: int((226553150 * 1023473145) / 5 + 3)
    Out[27]: 46374212988031352
    
    0 讨论(0)
提交回复
热议问题