问题描述
我需要将相当多的公式从 C 移植到 Python,反之亦然.确保过程中没有任何中断的最佳方法是什么?
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?
我希望我的问题听起来不太笼统.我主要担心自动 int/int = float 转换.
I hope my question doesn't sound too general. I am primarily worried about automatic int/int = float conversion.
推荐答案
您可以使用 //
运算符,它执行整数除法,但这并不是您对 C 的期望:
You could use the //
operator, it performs an integer division, but it's not quite what you'd expect from C:
引用自此处:
//运算符执行一种古怪的整数除法.当...的时候结果是肯定的,你可以想到它截断(不四舍五入)到 0小数点,但要小心
当整数除以负数时,//运算符将向上"舍入到最接近的整数.数学上说起来,它四舍五入向下",因为−6 小于 −5,但可能会跳闸如果你期待它,你起来截断为 -5.
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.
例如,-11//2
在Python中返回-6
,其中-11/2
在C中返回-5
.我建议编写一个模拟"C 行为的自定义整数除法函数并对其进行彻底的单元测试.
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.
我上面链接的页面也有一个指向 PEP 238 的链接有一些关于除法的有趣背景信息以及从 Python 2 到 3 的变化.有一些关于整数除法使用什么的建议,例如 divmod(x, y)[0]
和 int(x/y)
对于正数,也许你会在那里找到更多有用的东西.
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.
这篇关于Python 3 整数除法.如何使数学运算符与 C 一致的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!