3

I have this source code in Delphi, why I get this error "Floating point overflow." when I run the code? and how to correct it?

The error message:

enter image description here

The code:

procedure TForm1.Button1Click(Sender: TObject);
 var n, d, i, j, maxiter , iter: Integer;
 Lower,Upper : Double;
 X, V : TArray<TArray<Double>>;
 begin
  Lower := 0;
  Upper := 0.2;
  n := 100;
  d := 55;
  SetLength(V, n, d);
  SetLength(X, n, d);
  maxiter := 2000;
  iter := 1;

  for i:= 0 n-1 do
    for j:=0 to d-1 do
     begin
      X[i][j]:= Lower + (Upper - Lower) * Random;
      V[i][j] := 0.1 * X[i][j];
     end;

 while (iter <= maxiter) do
  begin
   for  i:= 0 to n-1 do
     for j:= 0 to D-1 do
       V[i][j]:= 5 * V[i][j] + 2.0 * Random;

   iter := iter +1;
  end;

end;
5
  • In the for loop you use the i index but it is uninitialized, so I would expect an Access violation, but ... You did not say on which line you get the error. Commented Oct 23, 2016 at 8:43
  • 1
    Enable warnings and hints and range checking and then deal with what comes from those changes. Commented Oct 23, 2016 at 8:57
  • @TomBrunberg How to initialized i in the for loop ?? The error in this line V[i][j] := 5 * V[i][j] + 2.0 * Random; Commented Oct 23, 2016 at 16:08
  • 1
    We can't guess what the code is meant to do. Did you heed my advice? Commented Oct 23, 2016 at 17:13
  • Well, in the for loop you access X[i][j] and V[i][j], but you never give a value to i, neither before the loop, nor within it. Maybe you forgot an outer for i:= 0 n-1 do loop. MBo answered your actual question, seems to be the correct answer. And for future, follow @David s comment, and do normal debugging. Commented Oct 23, 2016 at 18:02

1 Answer 1

10

Look here: V[i][j]:= 5 * V[i][j] + 2.0 * Random;

You make 2000 iterations, so your results might be as large as 7^2000 ~ 10^1690, but max value for Double type is about 10^308. So “Floating point overflow” error is exact diagnosis.

You could see V[] values about 10^307 in debug watch or immediate watch (mouse over V[]) when error occurred.

You can use 10-byte Extended type(probably not available for 64-bit compilers) to avoid overflow for these given variable values, but this is not good solution in general case.

Aside note: You did not set i index value for this code piece:

for j:=0 to d-1 do
  begin
    X[i][j]:= Lower + (Upper - Lower) * Random;
    V[i][j] := 0.1 * X[i][j];
  end;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.