-
Notifications
You must be signed in to change notification settings - Fork 0
/
sum of total Electric field
45 lines (35 loc) · 1.41 KB
/
sum of total Electric field
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
#include <iostream>
#include <cmath>
#include <limits>
using namespace std;
const double k = 9e9;
double electricField(double charge, double distance) {
return k * charge / (distance * distance);
}
int main() {
double length = 1.0;
double distance_to_charge = 0.5;
double q = 2e-9;
double desired_electric_field = 24.0; // Desired electric field value
double min_increment = length; // Initialize with maximum value
double min_error = numeric_limits<double>::max(); // Initialize with maximum error
for (int segments = 1; segments <= 1000; ++segments) {
double increment = length / segments; // Calculate increment
double total_electric_field = 0.0;
for (int i = 0; i < segments; ++i) {
double segment_position = (i + 0.5) * increment;
double distance = sqrt(segment_position * segment_position + distance_to_charge * distance_to_charge);
double e_field = electricField(q * increment, distance);
total_electric_field += e_field;
}
// Calculate error
double error = abs(total_electric_field - desired_electric_field);
// Check if error is smaller than previous smallest error
if (error < min_error) {
min_error = error;
min_increment = increment;
}
}
cout << "Smallest increment required: " << min_increment << " m" << endl;
return 0;
}