首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用DecimalRounding_JH1实现Delphi中的XE2舍入

用DecimalRounding_JH1实现Delphi中的XE2舍入
EN

Stack Overflow用户
提问于 2013-07-05 21:39:05
回答 1查看 599关注 0票数 0

由于Delphi中记录的舍入问题,我们正在使用XE2网站上提供的名为DecimalRounding_JH1的特殊舍入单元来实现真正的银行家舍入。可在此处找到该单元的链接:

DecimalRounding_JH1

使用本单元的DecimalRound函数处理包含大量小数位的数字

这是来自DecimalRounding_JH1单元的舍入例程。在我们的示例中,我们使用以下参数(166426800,12,MaxRelErrDbl,drHalfEven)调用此DecimalRound函数,其中maxRelErrDbl = 2.2204460493e-16 * 1.234375 *2

代码语言:javascript
复制
Function DecimalRound(Value: extended; NDFD: integer; MaxRelErr: double;
                         Ctrl: tDecimalRoundingCtrl = drHalfEven): extended;
{ The DecimalRounding function is for doing the best possible job of rounding
  floating binary point numbers to the specified (NDFD) number of decimal
  fraction digits.  MaxRelErr is the maximum relative error that will allowed
  when determining when to apply the rounding rule.  }
var i64, j64: Int64; k: integer; m, ScaledVal, ScaledErr: extended;
begin

  If IsNaN(Value) or (Ctrl = drNone)
    then begin Result := Value; EXIT end;

  Assert(MaxRelErr > 0,
      'MaxRelErr param in call to DecimalRound() must be greater than zero.');

{ Compute 10^NDFD and scale the Value and MaxError: }
  m := 1; For k := 1 to abs(NDFD) do m := m*10;
  If NDFD >= 0
    then begin
      ScaledVal := Value * m;
      ScaledErr := abs(MaxRelErr*Value) * m;
      end
    else begin
      ScaledVal := Value / m;
      ScaledErr := abs(MaxRelErr*Value) / m;
      end;

{ Do the diferent basic types separately: }
  Case Ctrl of
    drHalfEven: begin
      **i64 := round((ScaledVal - ScaledErr));**

最后一行是我们得到浮点错误的地方。

对于为什么会发生这个错误,您有什么想法吗?

EN

回答 1

Stack Overflow用户

发布于 2013-09-09 06:30:46

如果您得到一个异常,这意味着您不能在指定的错误范围内将您的值表示为double。

换句话说,maxRelErrDbl太小了。

尝试使用maxRelErrDbl = 0,0000000001或其他工具来测试我是否正确。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17490266

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档