Python 3 integer division. How to make math operators consistant with C

前端 未结 5 1329
野趣味
野趣味 2020-12-06 09:54

I need to port quite a few formulas from C to Python and vice versa. What is the best way to make sure that nothing breaks in the process?

I hope my question doesn\'

5条回答
  •  误落风尘
    2020-12-06 10:17

    You could use the // operator, it performs an integer division, but it's not quite what you'd expect from C:

    Quote from here:

    The // operator performs a quirky kind of integer division. When the result is positive, you can think of it as truncating (not rounding) to 0 decimal places, but be careful with that.

    When integer-dividing negative numbers, the // operator rounds “up” to the nearest integer. Mathematically speaking, it’s rounding “down” since −6 is less than −5, but it could trip you up if you were expecting it to truncate to −5.

    For example, -11 // 2 in Python returns -6, where -11 / 2 in C returns -5. I'd suggest writing and thoroughly unit-testing a custom integer division function that "emulates" C behaviour.

    The page I linked above also has a link to PEP 238 which has some interesting background information about division and the changes from Python 2 to 3. There are some suggestions about what to use for integer division, like divmod(x, y)[0] and int(x/y) for positive numbers, perhaps you'll find more useful things there.

提交回复
热议问题