a factor (leading an effect)
One day a college friend who had graduated many years ago asked in the class WeChat group if anyone could help write a piece of code to implement a function.
Then posted a snippet of the requirements to be fulfilled
I took a look at this description is simply a big head, programmers are more afraid of this kind of text without formatting, not even a line break, to be honest more than one look at the feeling of inexplicable annoyance. I didn't dare to speak, even if some students in the group had already started to name names, but never said a word.
come to sb's door
Then my classmates came directly to me, although graduated for 6 years with very few interactions, but the relationship in college is still quite good, so I said yes.
He then explained that it was a big coursework assignment for his younger brother in college, who majored in physics and was required to complete a physics assignment using coding. He sent over a document with a more detailed description of the physics assignment.
Physics Big Assignment:
This document is actually confusing to me, the first is that I haven't studied physics since high school, and it's a bit of a struggle to understand; the second is that I can't read so much of the physics knowledge can't be abstracted into the logic of the programming code.
Understanding Requirements
Combine that with the documentation he sent earlier and multiple communications from his brother to get the requirements right first.
It is simply as follows:
Randomize 30 points {a,b,c} a,b,c are randomly obtained from 0 to 10.
Requirementsa>b
q=a-b m=a+c
Do the following for each point
Known:
Points qCos(piy/2)dy Integral upper and lower bounds 0-1 + Integral qe^y*dy Upper and lower integral limits 1-2 = 1/2mv^2
Issue 1: Solve for the value of v
Known:
qvB=m*v^2/2R
Issue 2: Find the value of R
Known:
Angular velocity w = v/R Angle n = wt
If Pi/2<n<Pi,then x=R+RSin(Pi-n)+R*Cos(Pi-n)/Tan(Pi-n)
If n>Pi,then x=2R
If n<Pi/2, no achievement
Issue 3: Take the first three largest values in x.
Issue 4:
Draw their trajectories in the Cartesian coordinate system:
(x-R)2+y2=R^2
y>0,x<= R+RSin(Pi-n)
y=tan(Pi-n)(x- R+RSin(Pi-n)+RCos(Pi-n)/Tan(Pi-n))
Here finally figured out what the demand is, programmers are afraid that the demand is not clear, and meet the level of product managers can not, it is really suffering from the old crime.
Physics problems transformed into math problems
While figuring out what the demand is, it's beyond my ability to recall my high school physics knowledge and answer it correctly. In high school, I knew astronomy, geography, and physics in between, but now I just know how to ignore it. What I'm good at is putting formulas into code, if the formulas weren't even there, I couldn't figure it out.
Then I let him use to go through the physics problems, and with the process of doing the problems, I switched to code. Soon ah, he sent me the solution process.
There were some integral operations involved, and I tried to think back to the calculus I had studied years ago to find some answers in the depths of my memory.
Finally, the answers to the individual questions are organized:
Issue 1: Solve for the value of v , the formula for v is as above
Issue 2: To find the value of R, the formula for R is as above
Issue 3: Take the first three largest values in x.
Issue 4: Plot their trajectories in a right-angle coordinate system
write code
The next step is to write the code to solve the above problem. Knowing the process and formula for the answer, the next step is to write the code.
There is no doubt that python is the most appropriate language to accomplish this, and given his coding foundation, I asked for the code I wrote myselfclear-cut structure,clear explanatory note,shortness of function (math.),Variables are explicit,no showboating,No use of advanced data structures。
Generate 30 random numbers
def gen_30_point().
"""Generate 30 random numbers in groups of 3.""""
point_list = []
while len(point_list) < TOTAL.
a = (0, 10)
b = (0, 10)
# Require that a must be greater than b to generate a random number If a is less than or equal to b, then discard the set of data
if a <= b.
continue
c = (0, 10)
point_list.append((a, b, c))
return point_list
Calculating charge and electron mass from random numbers
def calculate_q_m(point_list):
"""according toa,b,cwork outq,m"""
q_m_list = []
for a, b, c in point_list:
q = (a - b) * ELECTRON_CHARGE
m = (a + c) * ELECTRON_QUALITY
q_m_list.append((q, m))
return q_m_list
Easily calculate v for problem 1
def calculate_v(q, m).
"""Calculate the velocity v."""
v = 2 * q * (2 / PI + E ** 2 - E) / m
v = (v)
return v
Calculate R for problem two
def calculate_r(q, m, v).
"""Calculate the radius R."""
r = m * v / (2 * B * q)
return r
Calculate x for problem 3
def calculate_x(n, r).
"""Calculate x."""
x = 0
if n > PI.
x = 2 * r
elif n < PI / 2.
x = 0
else: x = 0
x = r + r * (PI-n) + r * (PI-n)/(PI-n)
return x
Solving the graph of problem four under the right-angled coordinate system
def draw_track(n, r).
# Set the parameters of the circle
radius = r # radius
circle_center = (-r, 2) # Coordinates of the center of the circle, e.g. (2, 3)
# Generate the x and y coordinates of the circle
theta = (0, n, 100) # generate 100 points from 0 to 2π
x = circle_center[0] + radius * (theta)
y = circle_center[1] + radius * (theta)
# Draw the circle
(x, y, "k")
# Mark the center of the circle
(circle_center[0], circle_center[1], 'ko') # mark the center of the circle with a blue dot
# Set the axis range
(circle_center[0] - radius - 2, circle_center[0] + radius + 2)
(circle_center[1] - radius - 2, circle_center[1] + radius + 2)
# Straight line
x = (-30, x[-1], 20)
y = -x / (n) + r * (n) + 2 - r / (n) + r * (n) / (n)
(x, y)
# y = 2 horizontal lines
x = (-4 * r, 2 * r, 10)
y = ([2] * len(x))
(x, y, "k:")
# Coordinate system
new_ticks = (-5, 5, 11)
(new_ticks)
ax = ()
['right'].set_color('none')
['top'].set_color('none')
.set_ticks_position('bottom')
['bottom'].set_position(('data', 0))
.set_ticks_position('left')
['left'].set_position(('data', 0))
# Hide the 0 coordinate of the y-axis, otherwise it will be overlapped with the x-axis, which doesn't look good, and the 0 is at the 6th from the bottom
yticks = .get_major_ticks()
yticks[5].label1.set_visible(False)
# Set the axis title
('electronics track')
# Display the graph
()
When plotting a right-angle coordinate system, he found a problem with this formula and discussed and communicated with him
The final result
He ended up taking the code and completing the presentation of the assignment at the end of the semester and passed with flying colors.
wrap-up
You can see from the process, the difficulty of writing code is not high, mainly in the early understanding of the difficulty, whether it is physical knowledge, or calculus in the daily development of the project is really rare, more API interfaces, Redis, MySQL what. Through constant communication, a correct understanding of the needs, and then abstract the physical knowledge into mathematical content, and finally expressed in code, this process is not the epitome of a project development.
In the end, earn a meal 😁
Appendix Complete Code
"""
To run the method:
1. Install the dependency files
pip3 install matplotlib -i /simple
pip3 install numpy -i /simple
2. Run the code
python3 physics_code.py
Title:
Step 1: (complete)
Randomize 30 points {a,b,c} a,b,c are all randomly obtained from 0 to 10.
Require a>b, Calculate: q=a-b m=a+c
Step 2: Find V (complete)
Step 3: Find R (complete)
Step 4: Find X, take top3 (Finish)
Step 5: Draw the trajectory (Done)
"""
import math
import random
import as plt
import numpy as np
TOTAL = 30
PI = 3.14
E = 2.71
B = 10 ** -4
t = 2 * 10 ** -4
electron_charge = 1.602 * 10 ** -19
electron_quality = 1.672 * 10 ** -27
def gen_30_point():
"""Generate 30 random numbers in groups of 3.""""
point_list = []
while len(point_list) < TOTAL.
a = (0, 10)
b = (0, 10)
# Require that a must be greater than b to generate a random number If a is less than or equal to b, then discard the set of data
if a <= b.
continue
c = (0, 10)
point_list.append((a, b, c))
return point_list
def calculate_q_m(point_list).
"""Calculate q, m based on a,b,c""""
q_m_list = []
for a, b, c in point_list.
q = (a - b) * ELECTRON_CHARGE
m = (a + c) * ELECTRON_QUALITY
q_m_list.append((q, m))
return q_m_list
def calculate_v(q, m).
"""Calculate the velocity v."""
v = 2 * q * (2 / PI + E ** 2 - E) / m
v = (v)
return v
def calculate_r(q, m, v).
"""Calculate the radius R."""
r = m * v / (2 * B * q)
return r
def calculate_n(v, r).
"""Calculate n."""
n = v * T / r
return n
def calculate_x(n, r).
"""Calculate x."""
x = 0
if n > PI.
x = 2 * r
elif n < PI / 2.
x = 0
else: x = 0
x = r + r * (PI-n) + r * (PI-n)/(PI-n)
return x
def draw_track(n, r).
# Set the parameters of the circle
radius = r # radius
circle_center = (-r, 2) # Coordinates of the center of the circle, e.g. (2, 3)
# Generate the x and y coordinates of the circle
theta = (0, n, 100) # generate 100 points from 0 to 2π
x = circle_center[0] + radius * (theta)
y = circle_center[1] + radius * (theta)
# Draw the circle
(x, y, "k")
# Mark the center of the circle
(circle_center[0], circle_center[1], 'ko') # mark the center of the circle with a blue dot
# Set the axis range
(circle_center[0] - radius - 2, circle_center[0] + radius + 2)
(circle_center[1] - radius - 2, circle_center[1] + radius + 2)
# Straight line
x = (-30, x[-1], 20)
y = -x / (n) + r * (n) + 2 - r / (n) + r * (n) / (n)
(x, y)
# y = 2 horizontal lines
x = (-4 * r, 2 * r, 10)
y = ([2] * len(x))
(x, y, "k:")
# Coordinate system
new_ticks = (-5, 5, 11)
(new_ticks)
ax = ()
['right'].set_color('none')
['top'].set_color('none')
.set_ticks_position('bottom')
['bottom'].set_position(('data', 0))
.set_ticks_position('left')
['left'].set_position(('data', 0))
# Hide the 0 coordinate of the y-axis, otherwise it will be overlapped with the x-axis, which doesn't look good, and the 0 is at the 6th from the bottom
yticks = .get_major_ticks()
yticks[5].label1.set_visible(False)
# Set the axis title
('electronics track')
# Display the graph
()
if __name__ == "__main__".
point_list = gen_30_point()
q_m_list = calculate_q_m(point_list)
x_list = []
for q, m in q_m_list.
v = calculate_v(q, m)
r = calculate_r(q, m, v)
n = calculate_n(v, r)
x = calculate_x(n, r)
x_list.append((x, n, r))
print(f "q={q}, m={m}, v={v}, r={r}, n={n}, x={x}")
x_list.sort(reverse=True, key=lambda i : i[0])
for x, n, r in x_list[:3].
print(f "The three largest values in x: {x}")
for x, n, r in x_list[:3]::
draw_track(n, r)