What is the previous value in this loop?

Here is part of my code. The rest is just function definitions. I have a 20 x 20 array that records the temperature of the plate. I need to repeat the loop until no cell in the array changes by more than 0.1 degrees (I update the values ​​through each iteration). How would you track the largest change for any cell in the array to determine when to stop the iteration? I tried this right now, but it is not outputting correctly. I believe this is because I incorrectly define my previous one to compare the current one.

while (true) { bool update = false; for (int a = 1; a < array_size -1; a++) { for (int b = 1; b < array_size -1; b++) { hot_plate[a][b] = sum_cell(hot_plate, a, b); } } for (int a = 1; a < array_size-1; a++) { for (int b = 1; b < array_size-1; b++) { hot_plate_next[a][b]=sum_cell(hot_plate_next, a,b); if (abs(hot_plate_next[a][b] - hot_plate[a][b]) > 0.1) { update = true; } hot_plate_next[a][b] = hot_plate[a][b]; cout << hot_plate[a][b] << " "; } } if (!update) { break; } } 
+4
source share
2 answers

When you put:

  if (abs(hot_plate_next[a][b] - hot_plate[a][b]) < 0.1) { update = false; } 

inside the second nested for loop, you set "update" to false if the ANY of the cells has a difference of less than 0.1 between the current and previous checks, and not ALL cells as you wanted.

Update your code as follows:

  bool update = false; 

and

  if (abs(hot_plate_next[a][b] - hot_plate[a][b]) > 0.1) { update = true; } 

(I would put> =, but you said "so far no cell in the array will change by more than 0.1 degrees")

Edit as requested: to display the matrix cleanly, add the following line:

  cout << "\n"; 

here:

 for (int a = 1; a < array_size-1; a++) { for (int b = 1; b < array_size-1; b++) { hot_plate_next[a][b]=sum_cell(hot_plate_next, a,b); if (abs(hot_plate_next[a][b] - hot_plate[a][b]) > 0.1) { update = true; } hot_plate_next[a][b] = hot_plate[a][b]; cout << hot_plate[a][b] << " "; } cout << "\n"; // Add this line } 
+1
source

The problem is that you are overwriting update when the cell has a smaller change. In this case, any cell with a smaller change will stop the iteration.

Build your loop like this:

 float largest_change = 0.0f; do { largest_change = 0.0f; for (...) { float new_value = ... float change = abs(new_value - hot_plate[a][b]); if (change > largest_change) largest_change = change; hot_plate[a][b] = change; } } while (largestChange > 0.1f); 
+1
source

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


All Articles