Reputation: 45
I'm working on a project that deals with complex numbers, to explain more (a + bi) where "a" is the real part of the complex number and "b" is the imaginary part of it. (a and b are real numbers but "i" isn't)
I'm having a hard time with implementing a magnitude method, instead of getting back a real number as a double i get infinity.
This is what I'm trying to implement: | (a + bi) | = √(a^2 + b^2)
a snippet off my code
public double mag(){
/**
* Compute the magnitude of this complex number.
*
*/
//final double re is the real part
//final double I'm is the imaginary part
double mag = Math.sqrt(Math.pow(this.re, 2) + Math.pow(this.im, 2));
return mag;
}
say, if both real and imaginary numbers were Double.MAX_VALUE. why would mag return infinity instead of 1.8961503816218352E154 ?
Upvotes: 2
Views: 2479
Reputation: 1
In order to return 1.8961503816218352E154 do this
public double mag() {
double x = this.re;
double y = this.im;
return Math.hypot(x, y);
}
Upvotes: 0
Reputation: 4476
Infinity numbers are numbers larger than Double.MAX_VALUE or smaller than -Double.MAX_VALUE. 1.0/0.0 is infinite. So is 2*Double.MAX_VALUE.
Math.pow(Double.MAX_VALUE,2)
is obviously larger than Double.MAX_VALUE
. Squaring of a largest possible number will result into something that regular number system can't represent.
Math.sqrt(Math.pow(this.re, 2) + Math.pow(this.im, 2))
==> Math.sqrt(Math.pow(Double.MAX_VALUE, 2) + Math.pow(Double.MAX_VALUE, 2))
==> Math.sqrt(Infinity + Infinity)
==> Infinity
Before the sqrt can be calculated, the squaring of a double max value resulted into infinity. you can't find sqrt of an Infinity number, so what you got it perfectly valid.
Upvotes: 2
Reputation: 54702
for double values if the value exceeds Double.Max_value
then it returns infinity
. As the other answer has shown so in your case it will return infinity
. So for very big numbers you cannot do simple math operations. You better use BigDecimal
for this kind of operation.
Upvotes: 0