1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 |
#include <iostream> #include <vector> #include <iomanip> const int GRID_SIZE = 10; const double DIFFUSION_RATE = 0.1; class FluidDynamics { public: FluidDynamics() { grid.assign(GRID_SIZE, std::vector<double>(GRID_SIZE, 0.0)); newGrid.assign(GRID_SIZE, std::vector<double>(GRID_SIZE, 0.0)); } void setInitialCondition(int x, int y, double value) { if (x >= 0 && x < GRID_SIZE && y >= 0 && y < GRID_SIZE) { grid[x][y] = value; } } void simulateStep() { for (int i = 0; i < GRID_SIZE; ++i) { for (int j = 0; j < GRID_SIZE; ++j) { double total = grid[i][j]; int count = 1; if (i > 0) { total += grid[i - 1][j]; ++count; } if (i < GRID_SIZE - 1) { total += grid[i + 1][j]; ++count; } if (j > 0) { total += grid[i][j - 1]; ++count; } if (j < GRID_SIZE - 1) { total += grid[i][j + 1]; ++count; } newGrid[i][j] = (total / count) * (1 - DIFFUSION_RATE) + grid[i][j] * DIFFUSION_RATE; } } grid = newGrid; } void printGrid() const { for (const auto& row : grid) { for (double value : row) { std::cout << std::setw(6) << std::fixed << std::setprecision(2) << value << ' '; } std::cout << '\n'; } } private: std::vector<std::vector<double>> grid; std::vector<std::vector<double>> newGrid; }; int main() { FluidDynamics fluid; // Set initial conditions fluid.setInitialCondition(5, 5, 100.0); int steps; std::cout << "Enter number of simulation steps: "; std::cin >> steps; for (int i = 0; i < steps; ++i) { fluid.simulateStep(); std::cout << "Step " << i + 1 << ":\n"; fluid.printGrid(); std::cout << '\n'; } return 0; } |
Explanation
- Class Definition (
FluidDynamics
):- Private Members:
grid
: 2D vector representing the current state of the fluid on the grid.newGrid
: 2D vector for storing the next state of the fluid after each simulation step.
- Public Methods:
FluidDynamics()
: Constructor initializes the grid and newGrid with zeros.void setInitialCondition(int x, int y, double value)
: Sets the initial value at a specific position on the grid.- Ensures the coordinates are within bounds.
void simulateStep()
: Computes the next state of the fluid based on diffusion.- For each cell, calculates the average value of neighboring cells.
- Updates the newGrid with a mix of the old and new values, simulating diffusion.
- Copies newGrid to grid to update the current state.
void printGrid() const
: Prints the grid in a formatted manner.
- Private Members:
main
Function:- Creates a
FluidDynamics
object. - Sets an initial condition on the grid.
- Prompts the user for the number of simulation steps.
- Runs the simulation for the specified number of steps, printing the grid after each step.
- Creates a