While the loop and double action are weird

Attempts to solve the differential equation numerically (for the first time). My program asks for a bunch of parameters, and then calculates the amount of time needed to cool a bottle of wine to a given temperature. This is my main point:

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 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; } } 

Part of the while loop does this (using 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 

I don’t know why he is adding random decimal numbers. I also think (but I'm not 100%), the correct answer should be exactly 30 minutes, not 29.9. I do not see an obvious logical error here?

+4
source share
1 answer

You need to read this .

This is exactly how binary numbers and the IEEE floating point representation work.

You can no longer represent 0.1 in binary format than 1/3 in decimal form.

This is why you should not compare values ​​when using double or float; you need a tolerance on the absolute magnitude of the differences.

Similar to simple Euler integration of first-order ODEs for transient heat transfer for a concentrated mass. Make sure you understand how choosing a time step affects stability and accuracy.

+10
source

Source: https://habr.com/ru/post/1487724/


All Articles