Trying to solve a differential equation numerically (for the first time). My program asks for a bunch of parameters and then calculates the amount of time required to chill a bottle of wine to a given temperature. This is my main:
import java.util.Scanner;
public class Step2_lab11 {
public static int TAO = 50;
public static double DELTA_MINUTES = 0.1;
public static void main(String[] args) {
System.out.println("VINETS AVKYLNINGSTID \n");
System.out.println("Ange vinets temperatur:");
Scanner userIn = new Scanner(System.in);
double wineTemp = userIn.nextDouble();
System.out.println("Vinets önskade temperatur:");
double preferredTemp = userIn.nextDouble();
System.out.println("Kylens/frysens temperatur:");
double chillTemp = userIn.nextDouble();
WineChiller wineChiller = new WineChiller();
double elapsedTime = 0.0;
while(wineTemp > preferredTemp) {
elapsedTime = elapsedTime + DELTA_MINUTES;
double dT = wineChiller.getChillingTime(TAO, DELTA_MINUTES, chillTemp, preferredTemp, wineTemp);
wineTemp = wineTemp - dT;
System.out.println(elapsedTime);
}
}
}
And this is the WineChiller.java file:
public class WineChiller {
public WineChiller() {
}
public double getChillingTime(int TAO, double DELTA_MINUTES, double chillTemp, double preferredTemp, double wineTemp) {
double dT = (wineTemp - chillTemp) * DELTA_MINUTES / TAO;
return dT;
}
}
The Syso part of the while loop produces this (with wineTemp = 25, preferredTemp = 16, chillTemp = 5)
0.1
0.2
0.30000000000000004
....
29.300000000000146
29.400000000000148
29.50000000000015
29.60000000000015
29.700000000000152
29.800000000000153
29.900000000000155
No idea why it adds the random decimals. I also think (but I'm not 100%) the right answer should be exactly 30 minutes, not 29.9. Am I missing some obvious logic error here?
You need to read this.
This is just how binary numbers and IEEE floating point representation work.
You can no more represent 0.1 exactly in binary than you can 1/3 in decimal.
This is why you should not compare values when you use double or float; you need a tolerance for absolute value of differences.
Looks like a simple Euler integration of the first order ODE for transient heat transfer for a lumped mass. Make sure that you understand how time step choice affects stability and accuracy.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With