math namespace
Overview
Section titled “Overview”The math namespace groups together Pine Script’s advanced mathematical utilities. It provides constants (math.pi, math.e), rounding helpers, power/logarithmic functions, trigonometric conversions, and statistical helpers you can compose with ta.* indicators or your own calculations.
Most math.* functions output series float values. Cast back to int with int() when you need integers (e.g., for plot shapes or loops).
Common helpers
Section titled “Common helpers”| Group | Helper examples |
|---|---|
| Constants | math.pi, math.tau, math.e |
| Rounding | math.round(x), math.floor(x), math.ceil(x), math.round_to_mintick(x) |
| Algebra | math.min(a, b), math.max(a, b), math.abs(x), math.pow(x, y), math.sqrt(x) |
| Exponential/log | math.exp(x), math.log(x), math.log10(x) |
| Trigonometry | math.sin(x), math.cos(x), math.tan(x), math.asin(x), math.acos(x), math.atan(x) |
| Angle conversion | math.radians(deg), math.degrees(rad) |
Remarks
Section titled “Remarks”- All angles are expressed in radians. Convert a degree input with
math.radians(deg)and recover degrees viamath.degrees(rad). - When you need rolling statistics on series values, pair
mathutilities withta.*functions (e.g.,ta.variance,ta.stdev). - Use
math.round_to_mintick(x)when you need to align prices to the symbol’s minimum tick size.
Example
Section titled “Example”//@version=5indicator("math namespace example", overlay=false, max_labels_count=1)
len = input.int(50, "Window", minval=5)
// Convert close-to-close returns to z-score, then squash to [-1, 1] via atan.returns = math.log(close / close[1])mean = ta.sma(returns, len)variance = ta.variance(returns, len)sigma = math.sqrt(variance)
zScore = sigma > 0 ? (returns - mean) / sigma : 0.0bounded = (2.0 / math.pi) * math.atan(zScore)
plot(bounded, "Bounded z-score", color=color.new(color.blue, 0))hline(0, "Zero", color=color.gray)hline(0.5, "+0.5", color=color.new(color.green, 60))hline(-0.5, "-0.5", color=color.new(color.red, 60))
if barstate.islast label.new(bar_index, bounded, text = "pi ~= " + str.tostring(math.pi, format.mintick), style = label.style_label_left, textcolor = color.white, bgcolor = color.new(color.blue, 70))