程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python:實現lorenz transformation 洛倫茲變換算法(附完整源碼)

編輯:Python

Python:實現lorenz transformation 洛倫茲變換算法

from __future__ import annotations
from math import sqrt
import numpy as np # type: ignore
from sympy import symbols # type: ignore
# Coefficient
# Speed of light (m/s)
c = 299792458
# Symbols
ct, x, y, z = symbols("ct x y z")
ct_p, x_p, y_p, z_p = symbols("ct' x' y' z'")
# Vehicle's speed divided by speed of light (no units)
def beta(velocity: float) -> float:
""" >>> beta(c) 1.0 >>> beta(199792458) 0.666435904801848 >>> beta(1e5) 0.00033356409519815205 >>> beta(0.2) Traceback (most recent call last): ... ValueError: Speed must be greater than 1! """
if velocity > c:
raise ValueError("Speed must not exceed Light Speed 299,792,458 [m/s]!")
# Usually the speed u should be much higher than 1 (c order of magnitude)
elif velocity < 1:
raise ValueError("Speed must be greater than 1!")
return velocity / c
def gamma(velocity: float) -> float:
return 1 / (sqrt(1 - beta(velocity) ** 2))
def transformation_matrix(velocity: float) -> np.array:
return np.array(
[
[gamma(velocity), -gamma(velocity) * beta(velocity), 0, 0],
[-gamma(velocity) * beta(velocity), gamma(velocity), 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1],
]
)
def transform(
velocity: float, event: np.array = np.zeros(4), symbolic: bool = True
) -> np.array:
# Ensure event is not a vector of zeros
if not symbolic:
# x0 is ct (speed of ligt * time)
event[0] = event[0] * c
else:
# Symbolic four vector
event = np.array([ct, x, y, z])
return transformation_matrix(velocity).dot(event)
if __name__ == "__main__":
import doctest
doctest.testmod()
# Example of symbolic vector:
four_vector = transform(29979245)
print("Example of four vector: ")
print(f"ct' = {
four_vector[0]}")
print(f"x' = {
four_vector[1]}")
print(f"y' = {
four_vector[2]}")
print(f"z' = {
four_vector[3]}")
# Substitute symbols with numerical values:
values = np.array([1, 1, 1, 1])
sub_dict = {
ct: c * values[0], x: values[1], y: values[2], z: values[3]}
numerical_vector = [four_vector[i].subs(sub_dict) for i in range(0, 4)]
print(f"\n{
numerical_vector}")

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved