gpt4 book ai didi

delphi - Delphi 中通过 writeln/readln 实现实数精度

转载 作者:行者123 更新时间:2023-12-03 15:44:17 25 4
gpt4 key购买 nike

我的客户应用程序使用 writeln 和 readln 通过文本文件导出和导入相当多的 real 类型的变量。我尝试增加写入字段的宽度,因此代码如下所示:

writeln(file, exportRealvalue:30); //using excess width of field
....
readln(file, importRealvalue);

当我导出然后再次导入和导出并比较文件时,我在最后两位数字上发现了差异,例如(这里的实际位数可能有所不同,但你明白了):

-1.23456789012E-0002
-1.23456789034E-0002

这实际上对应用程序产生了影响,因此客户想知道我可以对此做些什么。现在我不确定只有写/读才能做到这一点,但我想在我再次深入堆栈之前我应该​​先提出一个简单的问题。我需要对此进行二进制处理吗?

这不是一个处理货币或其他东西的应用程序,我只是将值写入文件或从文件中读取值。我知道浮点有时有点奇怪,我认为其中一个例程(writeln/readln)可能会发生一些有趣的事情。

最佳答案

您可以尝试切换到扩展以获得更高的精度。正如所指出的, float 只有这么多有效数字的精度,因此仍然可以显示更多数字然后准确存储,这可能会导致您指定的行为。

来自 Delphi 帮助:

基本 Win32 实数类型

                                            | Significant | Size in Type     | Range                            | digits      | bytes---------+----------------------------------+-------------+----------Real     | -5.0 x 10^–324 .. 1.7 x 10^308   | 15–16       |   8  Real48   | -2.9 x 10^–39 .. 1.7 x 10^38     | 11-12       |   6   Single   | -1.5 x 10^–45 .. 3.4 x 10^38     |  7-8        |   4   Double   | -5.0 x 10^–324 .. 1.7 x 10^308   | 15-16       |   8   Extended | -3.6 x 10^–4951 .. 1.1 x 10^4932 | 10-20       |  10   Comp     | -2^63+1 .. 2^63–1                | 10-20       |   8   Currency | -922337203685477.5808..          |             |                     922337203685477.5807    | 10-20       |   8   

Note: The six-byte Real48 type was called Real in earlier versions of Object Pascal. If you are recompiling code that uses the older, six-byte Real type in Delphi, you may want to change it to Real48. You can also use the {$REALCOMPATIBILITY ON} compiler directive to turn Real back into the six-byte type. The following remarks apply to fundamental real types.

  • Real48 is maintained for backward compatibility. Since its storage format is not native to the Intel processor architecture, it results in slower performance than other floating-point types.
  • Extended offers greater precision than other real types but is less portable. Be careful using Extended if you are creating data files to share across platforms.

请注意,范围大于有效数字。所以你可以有一个更大的数字然后可以准确地存储。我建议四舍五入到有效数字以防止这种情况发生。

关于delphi - Delphi 中通过 writeln/readln 实现实数精度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/150011/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com