Skip to content

Commit 6b5fc36

Browse files
feat(backends): add backend_tan function for tangent computation
refactor(utils): improve numerical stability in compute_eta function - The backend_tan function was added to support tangent computation using the appropriate backend. - The compute_eta function was refactored to use a numerically stable formula for pseudorapidity calculation, avoiding issues when pz approaches ±p.
1 parent 274fe8a commit 6b5fc36

File tree

2 files changed

+18
-2
lines changed

2 files changed

+18
-2
lines changed

lvec/backends.py

+7-1
Original file line numberDiff line numberDiff line change
@@ -86,4 +86,10 @@ def backend_log(x, lib):
8686

8787
def backend_exp(x, lib):
8888
"""Compute exponential using appropriate backend."""
89-
return np.exp(x)
89+
return np.exp(x)
90+
91+
def backend_tan(x, lib):
92+
"""Compute tangent using appropriate backend."""
93+
if isinstance(x, (float, int)):
94+
return np.tan(x)
95+
return np.tan(x)

lvec/utils.py

+11-1
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,17 @@ def compute_mass(E, p, lib):
101101
def compute_eta(p, pz, lib):
102102
"""Compute pseudorapidity."""
103103
pt = compute_pt(p, pz, lib)
104-
eta = backend_atan2(pt, pz, lib)
104+
# Pseudorapidity is defined as η = -ln(tan(θ/2)) where θ is the polar angle
105+
# The polar angle θ is the angle between the momentum vector and the z-axis
106+
# θ = arctan(pt/pz), so we need to compute arctan(pt/pz) first
107+
# For numerical stability, use the formula η = 0.5 * ln((p + pz)/(p - pz))
108+
# This avoids issues when pz approaches ±p
109+
110+
# Handle the case where pz = ±p (θ = 0 or π)
111+
# When pz = p, η = ∞
112+
# When pz = -p, η = -∞
113+
# Use a numerically stable formula
114+
eta = 0.5 * backend_log((p + pz)/(p - pz + 1e-10), lib)
105115
if isinstance(p, (float, int)) and isinstance(pz, (float, int)):
106116
return float(eta)
107117
return eta

0 commit comments

Comments
 (0)