Delphi映射函数意外输出

2024-06-16 18:46:02 发布

您现在位置:Python中文网/ 问答频道 /正文

在Arduino库中发现了这个天才map函数。德尔菲写了同样的话:

procedure TForm1.Button1Click(Sender: TObject);
function map(x, in_min, in_max, out_min, out_max: Integer): extended;
begin
  result := (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
end;
var
  y, in_min, in_max, out_min, out_max: Integer;
  i: integer;
  m: extended;
begin
  in_min := 0;
  in_max := 6406963;
  out_min := 0;
  out_max := 474;
  y := 0;

  for i := in_min to in_max do begin
    m := map(i, in_min, in_max, out_min, out_max);
    if round(m) <> y then begin
        y := round(m);
        Memo1.Lines.Add(IntToStr(i) + ' = ' + FloatToStr(m));
    end;
  end;
end;

从中得到了一些有趣的结果,所以我用Python编写了同样的东西来检查和验证:

^{pr2}$

以下是我的结果片段:

DELPI                           EXPECTED (Python)
   6759 =    0,500044404813        6759  =    0.50004440481395
1358439 =  100,500047526418     1358439  =  100.50004752641775
2710119 =  200,500050648022     2710119  =  200.50005064802153
4061799 =  300,500053769625     4061799  =  300.5000537696253
4521370 =  334,500040034569     4521370  =  334.50004003456866
4530557 = -335,179597260043     4534887  =  335.50005486218663
5418335 = -269,499996488196     5413479  =  400.5000568912291
6405062 = -196,499949820219     6400205  =  473.50002957719596

那么,为什么我的Delphi代码会产生负数作为输出?应该怎么做才能纠正这个问题呢?在


Tags: 函数inextendedmapintegeroutminmax
3条回答

使用整型参数会导致溢出,从而解释负值。此子表达式:

(x - in_min) * (out_max - out_min)

只包含整数操作数,因此使用整数算术执行。这会溢出。产生负输出的第一个值是x = 4530557。让我们通过计算进一步挖掘:

^{pr2}$

并且该值大于high(Integer),因此溢出为负值。在

您应该在函数中使用浮点参数,以避免此陷阱。在

对于其他值,这些值与执行算术的精度相同。Delphi代码以64位扩展精度执行算术。53位双精度的Python代码。在

在我看来,最好避免64位扩展精度。它是非标准的,仅限于某些平台。它在32位x86上可用,但64位x64编译器将SSE单元用于浮点,并且该单元不支持64位扩展精度。最重要的是,数据类型的对齐导致读/写内存性能非常差。在

所以,如果你想要算术的可移植性,我建议你坚持53位双精度。停止使用Extended类型,改用Double。以及配置浮点单元以操作到53位精度。在

因此,最终结果是这个函数:

function map(const x, in_min, in_max, out_min, out_max: Double): Double;
begin
  result := (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
end;

整数溢出,应该使用Double。在

改变

function map(x, in_min, in_max, out_min, out_max: Integer): extended;

^{pr2}$

使用一个而不是扩展的,你会得到相同的结果

procedure TForm1.Button1Click(Sender: TObject);

  function map(x, in_min, in_max, out_min, out_max: Integer): Double;
  begin
    result := (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
  end;
var
  y, in_min, in_max, out_min, out_max: Integer;
  i: Integer;
  m: Double;
begin
  in_min := 0;
  in_max := 6406963;
  out_min := 0;
  out_max := 474;
  y := 0;

  for i := in_min to in_max do
  begin
    m := map(i, in_min, in_max, out_min, out_max);
    if round(m) <> y then
    begin
      y := round(m);
      Memo1.Lines.Add(IntToStr(i) + ' = ' + FloatToStr(m));
    end;
  end;
end;

编辑:请参阅大卫的答案以获得解释

相关问题 更多 >