Please forgive my ignorance, I'm a beginner.
Can anyone tell me why I am getting my error code in the if/else statement below? I think my result for the ln multiplication is is not exactly the same as the standard multiplication (there is a .00000000006 of a difference or something like that). Is there a work around for this? I have tried to use DecimalFormat but to no avail.
If I add:
DecimalFormat fmt = new DecimalFormat ("0.###");
to the tester and
if (fmt.format(z) != fmt.format(result)){
to the if statement I receive my own same error statement. What is wrong!?
Thank you very much.
Joe
import java.util.Scanner;
import java.lang.Math;
import java.text.DecimalFormat;
public class Logs {
//integer x field & encapsulation
private static double x;
// x encapsulation
public double getX(){
return x;
}
public void setX (double ex){
if (ex >= 0){
x = ex;
}
else{
System.out.println("You may not choose a negative number, 'x' = 0");
}
}
//integer y field
private static double y;
// y encapsulation
public double getY(){
return y;
}
public void setY (double why){
if (why >= 0){
y = why;
}
else{
System.out.println("You may not choose a negative number, 'y' = 0");
}
}
//tester
public static void main (String [] args){
Logs sample =new Logs();
Scanner var = new Scanner(System.in);
DecimalFormat fmt = new DecimalFormat ("0.###");
sample.setX (var.nextDouble());
sample.setY (var.nextDouble());
x = sample.getX();
y = sample.getY();
double z = (x*y);
double logX = Math.log(y);
double logY = Math.log(x);
double logZ = (logX +logY);
double result = (Math.exp(logZ));
if (z != result){
System.out.printf("%s", "Incorrect answer: be a better coder");
}
else {
System.out.printf("%s %.3d %s %.3d %s %.3d",
"The product of the values you chose is: ", + z,
"\nln(x) + ln(y) is: ", + logZ,
"\nCompute to e: ", + result);
}
}
}
You're comparing string references rather than their values, and you want String.equals()
e.g. z.equals(result)
However, I think what you're trying to do is compare two decimal numbers to a certain precision. It's more intuitive to calculate the difference and determine if that's within an acceptable error bound e.g.
if (Math.abs(z - result) < 0.01) {
// ok
}
See Math.abs(double a) for more details