John Riselvato
John Riselvato

Reputation: 12904

Illegal division by zero

@xyVal = (4,4,6,6,10,12,18,22,24,28,30);
@yVal = (176,178,180,184,192,202,210,218,224,232,238);

@xxVal = (9,9,9,9,9 ,11,13,15,17,19,19);
@xVal = (168,166,164,162,158,150,142,134,122,116,110);

for ($i = 0; $i <  scalar(@xVal); $i++){
    for ($i = 0; @xyVal[$i] < @xxVal[$i]; $i++){
        @yNewVal = @yVal[$i-1] + (@yVal[$i] - @yVal[$i-1])*(@xxVal[$i] - @xyVal[$i-1])/(@xyVal[$i] - @xyVal[$i-1]);
    }
}
print @yNewVal;

I understand why its giving me the error Illegal division by zero about line 9 (the @yNewVal = ...)

I want the array to have 0 in it if there is a division between zeros. What am I doing wrong? So, how can I avoid that my application crashes when there is a division by zero?

Upvotes: 0

Views: 6441

Answers (4)

zellio
zellio

Reputation: 32484

You can perform a try/catch using eval and conditional operators.

eval {
    @yNewVal = @yVal[$i-1] + (@yVal[$i] - @yVal[$i-1])*(@xxVal[$i] - @xyVal[$i-1])/(@xyVal[$i] - @xyVal[$i-1]);
    1;
} or do {
    @yNewVal = (0);
}; 
print @yNewVal;

Though, your phrase is returning a scalar value and putting it into an array variable. So you may want to re-factor that.

Upvotes: 1

MisterEd
MisterEd

Reputation: 1735

You could say:

@yNewVal = ($_ = @xyVal[$i] - @xyVal[$i-1]) == 0 ? 0 : @yVal[$i-1] + (@yVal[$i] - @yVal[$i-1])*(@xxVal[$i] - @xyVal[$i-1])/$_;

Upvotes: 2

MusiGenesis
MusiGenesis

Reputation: 75296

Your divisor on that line is @xyVal[$i] - @xyVal[$i-1], so any case where you have two identical adjacent values in @xyVAl (e.g. 4,4) will result in a 0, and thus a divide-by-zero error.

Upvotes: 4

sharpner
sharpner

Reputation: 3937

well if i understand you correctly:

if (@xyVal[$i] == @xyVal[$i-1]) 
@yNewVal = 0; 
else 
@yNewVal = @yVal[$i-1] + (@yVal[$i] - @yVal[$i-1])*(@xxVal[$i] - @xyVal[$i-1])/(@xyVal[$i] - @xyVal[$i-1]);

Upvotes: 1

Related Questions