Arnold
Arnold

Reputation: 4840

Division by zero when using Ln or Exp function

In my code I sometimes get a division by zero. The debugger consistently points to a line containing an Ln or Exp function.

Using the Ln function. As you can see there is no division at all in this section. vsn stands for very small number and equals 1.0e-100.

 if a3 [row] <= 0 then a := vsn else
 if a3 [row] >= 1 then a := 1 - vsn
                  else a := a3 [row];
 costTerm := costTerm -1 * y [row] * Ln (a) -
                  (1 - 1 * y [row]) * Ln (1 - a);

Using the Exp function: here a division exists but a fail to see how this can generate a division by zero error.

function TBack_Prop.g (value: double): double;
begin
   Result := 1 / (1 + exp (-value));
end; // g //

Any idea what I am doing wrong?

Upvotes: 0

Views: 1079

Answers (2)

Ast Pace
Ast Pace

Reputation: 152

Not having the rep to make a comment, I must comment by way of an answer.

The smallest workable size for vsn is 1.0e-16 when using real or double precision. This takes care of the first question answered by @Sebastion.

The second question is whether

(1 + exp(-value))

gives a result of 0, hence division by zero. Can't happen.
However, a typo

(1 - exp(-value)) or (1 - exp(value))

could certainly be the culprit, but that's just grabbing at straws.

Upvotes: 2

Sebastian Z
Sebastian Z

Reputation: 4730

ln(0) will raise a division by zero. In your code you pass 0 to the ln function.

var
  I: Double;
  vsn: Double;
begin
  I := 1.0;
  vsn := 1.0e-100;
  I := I - vsn;
  ln(1 - I);
end;

Then line I := I - vsn does not really do anything. A double has only 15-16 significant digits, so the value of vsn does not modify I. Then you have ln(1-1) which is calculating ln(0).

exp(x) cannot become less than 0. So I cannot explain the division by 0 in TBack_Prop.g. I'd say the exception happens somewhere else.

Upvotes: 6

Related Questions