(La)TeX Base 10 定点运算
我正在尝试在 (La)TeX 中实现十进制算术。我正在尝试使用维度来存储值。我希望算术精确到一些(固定)小数位数。如果我使用 1pt 作为基本单位,那么这会失败,因为 \divide 向下舍入,所以 1pt / 10 给出 0.09999pt。如果我使用 1000sp 之类的东西作为基本单位,那么我可以使用 3 位小数进行定点算术,但我无法找到一种简单的方法来格式化数字。如果我尝试将它们转换为 pt,这样我就可以使用 TeX 的显示机制,我对 \divide 也有同样的问题。
我该如何解决或解决这个问题?
I'm trying to implement decimal arithmetic in (La)TeX. I'm trying to use dimens to store the values. I want the arithmetic to be exact to some (fixed) number of decimal places. If I use 1pt as my base unit, then this fails, because \divide rounds down, so 1pt / 10 gives 0.09999pt. If I use something like 1000sp as my base unit, then I get working fixed point arithmetic with 3 decimal places, but I can't figure out an easy way to format the numbers. If I try to convert them to pt, so I can use TeX's display mechanism, I have the same problem with \divide.
How do I fix this problem, or work around it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
fp 包为 LaTeX 提供定点运算。 LaTeX3 项目目前正在实现类似的东西,作为 expl3 包的一部分。该代码当前不在 CTAN 上,但可以从 SVN 获取(或者在下次从 SVN 更新到 CTAN 时出现)。
The fp package provides fixed point arithmetic for LaTeX. The LaTeX3 Project are currently implementing something similar as part of the expl3 bundle. The code is currently not on CTAN, but can be grabbed from the SVN (or will appear when the next update from the SVN to CTAN takes place).
我会将所有值表示为整数并适当缩放它们。例如,当您需要三位十进制数字时,
0.124
将表示为124
。这很好,因为加法和减法是微不足道的。将两个数字a
和b
相乘时,您必须将结果除以1000
才能得到正确的表示形式。除法是将结果乘以1000
。您仍然需要正确解决舍入问题,但这并不是很困难。至少如果您没有接近最大可表示整数(我不记得它是
2^31-1
还是2^30-1
)。下面是一些代码:
这些操作以三寄存器机为模型,其中第一个是目标,另外两个是操作数。乘法和除法之后的舍入(包括非常大或非常小的数字的极端情况)留给您作为练习。
I would represent all the values as integers and scale them appropriately. For example, when you need three decimal digits,
0.124
would be represented as124
. This is nice because addition and subtraction are trivial. When multiplying two numbersa
andb
, you would have to divide the result by1000
to get the proper representation. Dividing works by multiplying the result with1000
.You still have to get the rounding issues correct, but this isn't very difficult. At least if you don't get near the maximum representable integer (I don't remember if it's
2^31-1
or2^30-1
).Here is some code:
The operations are modeled after a three register machine, where the first is the destination and the other two are the operands. The rounding after the multiplication and division, including corner cases for very large or very small numbers are left as an exercise to you.