惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

IT之家
IT之家
H
Help Net Security
GbyAI
GbyAI
博客园_首页
G
Google Developers Blog
Microsoft Security Blog
Microsoft Security Blog
博客园 - 【当耐特】
月光博客
月光博客
美团技术团队
B
Blog RSS Feed
博客园 - 三生石上(FineUI控件)
WordPress大学
WordPress大学
博客园 - 叶小钗
有赞技术团队
有赞技术团队
T
The Blog of Author Tim Ferriss
Engineering at Meta
Engineering at Meta
Google DeepMind News
Google DeepMind News
Y
Y Combinator Blog
宝玉的分享
宝玉的分享
Microsoft Azure Blog
Microsoft Azure Blog
罗磊的独立博客
云风的 BLOG
云风的 BLOG
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
P
Proofpoint News Feed

cuihao->blog

留言板备份 - cuihao->blog 局域网中通过 TUN 和软路由实现链路聚合 - cuihao->blog 网页中的 <body> 和 <html> 元素及其样式 雾霾中的星空 - cuihao->blog 把 /usr/share 压成 squashfs,以及写 systemd 的 mount 单元 一些关于读书的事 - cuihao->blog Archlinux on ThinkPad L430 - cuihao->blog NetworkManager 配合使用 chnroutes (至少适用于 Arch) 【火狐三则】增强组件的PKGBUILD;不错的dial插件;同步profile到内存盘 - cuihao->blog unzip 6.10b测试版,解决ZIP乱码问题 - cuihao->blog 最后还是堕落到宋体了 - cuihao->blog
负整数的整除和取余运算 - cuihao->blog
cuihao · 2013-03-30 · via cuihao->blog

负整数的整除和取余运算

负整数间是怎么整除和取余数的呢?

数学上貌似没定义,但计算机确实能算。于是就试了试,想总结一下规律。

一不小心发现,C/C++ 和 Python 下的结果是不同的:

  C/C++ Python 精确值
-14/3 -4 -5 -4.67
-14%3 -2 1 /
14/-3 -4 -5 -4.67
14%-3 2 -1 /
-14/-3 4 4 4.67
-14%-3 -2 -2 /

总结规律如下:

  1. 两种语言中,商和余数都符合 被除数=商x除数+余数 这一数学规律。
  2. 两种语言中,整除的方法不同:C/C++ 是向零取整(负数向上、正数向下取整),Python 是下取整

以 n/3 和 n%3 为例,看看这两种处理方法的区别。

C 的情况,两种运算结果都关于0对称和反号

n -5 -4 -3 -2 -1 0 +1 +2 +3 +4 +5
-1 -1 -1 0 0 0 0 0 1 1 1
余数 -2 -1 0 -2 -1 0 1 2 0 1 2

Python 的情况,运算结果是完全连续的:

n -5 -4 -3 -2 -1 0 +1 +2 +3 +4 +5
-2 -2 -1 -1 -1 0 0 0 1 1 1
余数 1 2 0 1 2 0 1 2 0 1 2

不知道那种在数学上更好用。个人觉得 Python 的处理方式更优美一些吧。

至于其他语言的处理方法,应该也出不了这两种。我所知道的:

  • C/C++ “向零取整式整除”:C/C++、Java、bash
  • Python “下取整式整除”:Python、Perl、Lua