Python 3 整数除法.如何使数学运算符与 C 一致 [英] Python 3 integer division. How to make math operators consistant with C

查看:33
本文介绍了Python 3 整数除法.如何使数学运算符与 C 一致的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将相当多的公式从 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小数点,但要小心

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.

当整数除以负数时,//运算符将向上"舍入到最接近的整数.数学上说起来,它四舍五入向下",因为−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 一致的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆