# 整数与浮点运算的范式差异

Original title: Float and integer arithmetic follow two different paradigms

> Hacker News story 49965117 · language: zh · submitted 2026-10-05
> Web version: https://zeli.app/zh/story/49965117
> About this feed: https://zeli.app/llms.txt · Agent guide: https://zeli.app/skill.md

▲ 67 · by [ibobev](<https://news.ycombinator.com/user?id=ibobev>) · 💬 19
[original](<https://blog.pkh.me/p/49-float-and-integer-arithmetic-follow-two-different-paradigms.html>) · [HN discussion](<https://news.ycombinator.com/item?id=49965117>)

## Summary

在处理浮点数时，我们常错误地沿用整数运算的防御性编程习惯，试图在灾难发生前进行预防。实际上，IEEE-754标准下的浮点运算拥有完全不同的安全范式：错误会生成NaN或无穷大并自然传播，而不会导致程序崩溃。盲目使用FLT_EPSILON等阈值检查往往无效且多余，正确的做法是直接验证最终结果是否为有限数（isfinite）。这种机制让浮点运算在处理复杂公式时比整数运算更加健壮，尽管数值不稳定性依然存在，但无需在每一步都进行繁琐的预检。

## Key quote

> 浮点数确实存在诸多缺陷，但就我个人观点而言，这反而让它们比整数运算更加便捷和安全。

## HN discussion (19 comments)

### [weinzierl](<https://news.ycombinator.com/item?id=50006127>)

> 所谓的“整数运算范式”意味着要么在（几乎）每次运算后进行检查，要么就得忍受可能错误的结果。
>
> 第一种做法效率极低，第二种则完全是错的（尽管极其常见）。
>
> 这很可悲，因为整数完全没有理由不能遵循 OP 所称的“浮点范式”。它甚至不必很慢。大多数现代处理器（如果我们忽略 x86）都支持某种形式的粘滞算术标志（sticky arithmetic flags）。遗憾的是，编程语言并不支持它们，所以它们也就没有被使用。
>
> 此外，关于除以零所受到的特殊对待，也值得讨论一番。

### [a_e_k](<https://news.ycombinator.com/item?id=50008567>)

> 对于浮点部分，请小心 `-ffinite-math-only`。如果启用，`isfinite()` 可能会被编译优化掉，并假设其结果为真（`isnan()` 和 `isinf()` 也会有类似的假设）。
>
> 而 `-ffinite-math-only` 会被 `-ffast-math` 启用，后者又会被 `-Ofast` 启用。

### [dooglius](<https://news.ycombinator.com/item?id=50006470>)

> 顺便一提，可以在运行时以零开销配置浮点异常，参见 `man 3 fenv`

---

## Cite

- Page: https://zeli.app/zh/story/49965117
- Date: 2026-10-05
- Source: blog.pkh.me (https://blog.pkh.me/p/49-float-and-integer-arithmetic-follow-two-different-paradigms.html)
- Hacker News: https://news.ycombinator.com/item?id=49965117

## Other languages

- en: https://zeli.app/story/49965117 · markdown: https://zeli.app/story/49965117.md
- ja: https://zeli.app/ja/story/49965117 · markdown: https://zeli.app/ja/story/49965117.md
- ko: https://zeli.app/ko/story/49965117 · markdown: https://zeli.app/ko/story/49965117.md
- de: https://zeli.app/de/story/49965117 · markdown: https://zeli.app/de/story/49965117.md
- es: https://zeli.app/es/story/49965117 · markdown: https://zeli.app/es/story/49965117.md
- ru: https://zeli.app/ru/story/49965117 · markdown: https://zeli.app/ru/story/49965117.md
