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

前端 未结 5 1326
野趣味
野趣味 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:15

    Apologize, I'm answering to the opposite direction, but I can't find such Question, so anyway:

    Since Python3 divmod (or //) integer division requires remainder to have the same sign as divisor at non-zero remainder case, it's inconsistent with many other languages (quote from http://anh.cs.luc.edu/handsonPythonTutorial/integer.html)

    To have your "C-like" result same as Python, you should compare the remainder result with divisor (suggestion: by xor on sign bits equals to 1, or multiplication with negative result), and in case it's different, add the divisor to the remainder, and subtract 1 from the Quotient

            // Python Divmod requires remainder with the same sign as Divisor for 
            // non-zero remainder
    
            // Assuming isPyCompatible is a flag to distinguish c/py mode
            isPyCompatible *= (int)remainder;
            if (isPyCompatible)
            {
                int32_t xorRes = remainder ^ divisor;
                int32_t andRes = xorRes & ((int32_t)((uint32_t)1<<31));
                if (andRes)
                {
                    remainder += divisor;
                    quotient -= 1;
                }
            }
    

    (credit to Gawarkiewicz M. for pointing this out)

提交回复
热议问题