Reputation: 41
I am trying to output NaN in string format when x is NaN. However, the console throws up String cannot be converted to double error when I am trying to return string of "NaN" when Double.isNaN is true. I tried parsing string r as a double using Double.parseDouble() but to no avail.
Here is my code:
public static double heaviside(double x) {
String r = "NaN";
r = Double.parseDouble(r);
double result;
if (Double.isNaN(x)) return r;
else if (x < 0.0) return result = 0.0;
else if (x == 0.0) return result = 0.5;
else return result = 1.0;
}
Console output
ActivationFunction.java:6: error: incompatible types: double cannot be converted to String r = Double.parseDouble(r); ^ ActivationFunction.java:8: error: incompatible types: String cannot be converted to double if (Double.isNaN(x)) return r; ^
Upvotes: 0
Views: 1501
Reputation: 3131
You problem comes from the fact, that you try to assign double
to String
variable. r
is defines as String
and Double.parseDouble(r)
returns double
. It will work if you assing it to result
instead, like so: double result = Double.parseDouble(r);
However, there is no need to parse new double
from String
in the first place. You want to return NaN
when x == NaN
. You can just return x
in that case because, well, x
is NaN
. No need for another variable, parsing and all of that.
Upvotes: 3
Reputation: 1815
You are trying to convert String into double and storing its value in r
which is a type of String
.
You should create another variable of double
type and can store that value in that like this:
public static double heaviside(double x) {
String r = "NaN";
double d = Double.parseDouble(r);
double result;
if (Double.isNaN(x)) return d;
else if (x < 0.0) return result = 0.0;
else if (x == 0.0) return result = 0.5;
else return result = 1.0;
}
I hope it will help you. Happy coding..!
Upvotes: 1
Reputation: 145
"NaN" is not a double, you can't convert it to double and not return x
because Java returns an exception on line 2 of your code and does not continue to run the rest of the code
Upvotes: 0