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 |
#include <iostream> #include <vector> #include <cmath> // Define a structure for a magnetic pole struct MagneticPole { double x, y; // Position of the magnetic pole double strength; // Strength of the magnetic pole }; // Define a structure for a magnetic field vector struct MagneticFieldVector { double x, y; // Direction components double magnitude; // Magnitude of the field }; // Function to calculate the magnetic field vector at a given point MagneticFieldVector calculateField(const std::vector<MagneticPole>& poles, double px, double py) { MagneticFieldVector field = {0.0, 0.0, 0.0}; for (const auto& pole : poles) { double dx = px - pole.x; double dy = py - pole.y; double distance = std::sqrt(dx * dx + dy * dy); if (distance > 0) { double fieldStrength = pole.strength / (distance * distance); field.x += fieldStrength * (dx / distance); field.y += fieldStrength * (dy / distance); field.magnitude += fieldStrength; } } return field; } // Function to display the magnetic field vector void displayField(const MagneticFieldVector& field) { std::cout << "Magnetic Field Vector:\n"; std::cout << "Direction: (" << field.x << ", " << field.y << ")\n"; std::cout << "Magnitude: " << field.magnitude << "\n"; } int main() { // Define magnetic poles std::vector<MagneticPole> poles = { {0.0, 0.0, 10.0}, // Pole at (0, 0) with strength 10 {5.0, 5.0, 5.0} // Pole at (5, 5) with strength 5 }; // Define a point to calculate the magnetic field double pointX = 3.0; double pointY = 3.0; // Calculate the magnetic field at the point MagneticFieldVector field = calculateField(poles, pointX, pointY); // Display the magnetic field vector displayField(field); return 0; } |
Explanation
- MagneticPole Structure:
- Represents a magnetic pole with its position
(x, y)
Advertisementstrength
.
- Represents a magnetic pole with its position
- MagneticFieldVector Structure:
- Represents a magnetic field vector with direction components
(x, y)
and magnitude.
- Represents a magnetic field vector with direction components
- calculateField Function:
- Takes a vector of magnetic poles and a point
(px, py)
Advertisement - Calculates the magnetic field vector at the point by summing the contributions of each pole.
- Uses the formula
fieldStrength = pole.strength / (distance * distance)
to calculate the contribution from each pole, where distance is the Euclidean distance between the point and the pole.
- Takes a vector of magnetic poles and a point
- displayField Function:
- Displays the magnetic field vector, including its direction and magnitude.
- main Function:
- Defines a set of magnetic poles.
- Defines a point where the magnetic field is to be calculated.
- Calls
calculateField
to compute the magnetic field at the point. - Displays the result using
displayField
.