# no physipy → we need to keep track of the unit everywhere
my_weight_kg = 75
my_height_m = 1.89defbmi_calculator(weight_kg, height_m):
"Compute Body-Mass-Index from weight and height."return weight_kg / height_m**2print(bmi_calculator(my_weight_kg, my_height_m))
# notice that the output is pure, unit-less number, while it is actually kg-per-meter-squared# 20.99605274208449
现在让我们看看使用 physipy 的代码是什么样的:
from physipy import kg, m # define physical quantities that are unit aware
my_weight = 75 * kg
my_height = 1.89 * m
defbmi_calculator(weight, height):
"Compute Body-Mass-Index from weight and height."return weight / height**2print(bmi_calculator(my_weight, my_height))
# 20.99605274208449 kg/m**2
# retrieve the unitsfrom physipy import units # units is just a dict
cm = units['cm']
g = units['g']
print(bmi_calculator(75000*g, 189*cm))
# 20.99605274208449 kg/m**2
因此,我们得到了相同的输出值,同时我们能够指定变量在其他单位中。
使用 numpy 数组进行牛顿运动定律
我们在这里演示如何仅使用常规乘法运算符(类似于浮点数和整数)将单位附加到常规 NumPy 数组上:
import numpy as np
from physipy import m, kg, s
mass = np.array([10, 20, 30]) * kg # mass
a = 2 * m / s**2# acceleration# Calculate force using Newton's Second Law : force = mass * acceleration
F = mass * a
print(F)
# [ 200. 800. 1800.] kg**2/s**2 # 1 kg*s/s**2 is equivalent to 1 Newton
import numpy as np
from physipy import units
V = units['V']
ohm = units['ohm']
V = 12 * V # voltage
R = np.arange(1*ohm, 5*ohm) # array with unit ohm# Calculate current using Ohm's Law
I = V / R
print(I)
# [12. 6. 4. 3.] A# If for some reason you forgot the unit of I, physipy knows and attaches# it to I for you - you get an output in Amps for free !
import numpy as np
from physipy import constants, kg, units
# constants is just a dict of physical constants
c = constants['c']
J = units['J']
masses = np.array([
9.1093837E-31, # mass of electron1.673E-27, # mass of proton1.675E-27# mass of neutron
]) * kg
# Calculate energy using Einstein's equation
E = masses * c**2# indexing works just as usual, with the added output energy unitprint(E[0])
# enery for proton : 8.187105775475753e-14 kg*m**2/s**2print(E)
# [8.18710578e-14 1.50361741e-10 1.50541492e-10] kg*m**2/s**2# changing the display unit to Joule
E.favunit = J
print(E[0])
# 8.187105775475753e-14 Jprint(E)
# [8.18710578e-14 1.50361741e-10 1.50541492e-10] J
import numpy as np
from physipy import m, s, units
cm = units['cm'] # we are using cm as the favunit# Constants
initial_height = 100 * m # Initial height of the object
gravity = 9.81 * m / s**2# Acceleration due to gravity# Time samples
time_samples = np.linspace(0, 3, 50) * s # Time samples from 0 to 3 secondsdefcalculate_height(time_samples):
height = initial_height - 0.5 * gravity * time_samples**2
height.favunit = cm
return height
# Calculate heights for each time sample
heights = calculate_height(time_samples)
# Print time samples and corresponding heightsfor t, h inzip(time_samples, heights):
print(f"Time: {t}, Height: {h}")
# Time: 0.0 s, Height: 10000.0 cm# ...# Time: 3.0 s, Height: 5585.5 cm
import numpy as np
import matplotlib.pyplot as plt
from physipy import units, s, setup_matplotlib, constants
cm = units['cm'] # centimeter
ms = units["ms"] # millisecond
g = constants['g']
# this makes matplotlib aware of physipy
setup_matplotlib()
time = np.linspace(0, 10, 100) * s # Time values
time.favunit = ms
velocity = g * time # Velocity as a function of time (assuming constant acceleration)
displacement = 0.5 * g * time**2# displace from origin position
displacement.favunit = cm
# Plotting
fig, ax = plt.subplots(figsize=(10, 4))
ax.plot(time, displacement, label="Displacement", color="blue")
ax2 = ax.twinx()
ax2.plot(time, velocity, label="Velocity", linestyle=" - ", color="red")
注意,轴标签上添加了一些单位,但没有显式调用 set_xlabel/set_ylabel。
总结
希望这些例子能帮助你理解如何使用 physipy 的基础知识。你应该记住以下事项:
使用 physipy 最简单的方法是导入一些单位/常量,这些单位/常量存储在经典的 Python 字典中,使用 from physipy import units, constants。注意,国际单位制(Système International units)可以直接使用 from physipy import m, s, kg。