Last active
July 27, 2018 10:21
-
-
Save IvanaGyro/cdc53b156107333d2743930299cd024e to your computer and use it in GitHub Desktop.
Calculate the electric field induced from a spherical uniform charge distribution
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#-*- coding:utf-8 -*- | |
import random | |
import math | |
from functools import reduce | |
def random_point_in_sphere(r): | |
while True: | |
x = random.uniform(-r, r) | |
y = random.uniform(-r, r) | |
z = random.uniform(-r, r) | |
if x*x + y*y + z*z <= r*r: | |
return (x, y, z) | |
def calcu_field(pointNum, sphereR, target): | |
points = [random_point_in_sphere(sphereR) for i in range(0, pointNum)] | |
Ex, Ey, Ez = 0, 0, 0 | |
for point in points: | |
x, y, z = map(lambda a, b: a - b, target, point) | |
d2 = x*x + y*y + z*z | |
d = math.sqrt(d2) | |
E = k * q / d2 | |
Ex += E * x / d | |
Ey += E * y / d | |
Ez += E * z / d | |
return Ex, Ey, Ez | |
# Coulomb's constant 8.987 * 10 ** 9 (N*m^2/C^2) in real world | |
k = 1 | |
# magnitude of electric charge per point (in Coulomb) | |
q = 1 | |
# radius of the spherical uniform charge distribution | |
a = 50 | |
# location of the target | |
targetX = 30 | |
targetY = 0 | |
targetZ = 0 | |
# number of the point with charge | |
pointNum = 100000 | |
target = (targetX, targetY, targetZ) | |
r = math.sqrt(reduce(lambda x, y: x + y**2, (0,) + target)) | |
if r < a: | |
EFormula = k * pointNum * q / a / a / a * r | |
else: | |
EFormula = k * pointNum * q / r / r | |
for i in range(0, 1): | |
print('Calculation:', calcu_field(pointNum, a, target)) | |
print('Formula:', EFormula) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment