Table of Contents
Returns the square root of a number.
1. Description
The sqrt operator pops a non-negative number from the operand stack and pushes its square root. The operand must be non-negative; negative values cause a rangecheck error. The result is always a real number.
This is a Level 1 operator, available in all PostScript implementations.
5. Examples
5.1. Basic Usage
% Perfect squares
4 sqrt % → 2.0
9 sqrt % → 3.0
16 sqrt % → 4.0
25 sqrt % → 5.0
% Non-perfect squares
2 sqrt % → 1.41421...
10 sqrt % → 3.16228...
6. Advanced Examples
6.1. Normalize Vector
/normalize { % [x y] -> [nx ny]
dup magnitude % [x y] mag
dup 0 eq {
pop pop [0 0]
} {
exch aload pop % mag x y
2 index div % mag x (y/mag)
3 1 roll div % (y/mag) (x/mag)
exch 2 array astore
} ifelse
} def
[3 4] normalize % → [0.6 0.8]
6.2. Quadratic Formula
/quadratic { % a b c -> root1 root2 or null
% Solve ax² + bx + c = 0
3 copy % a b c a b c
pop dup mul % a b c b²
4 4 index mul % a b c b² 4a
5 -1 roll mul sub % a b (b²-4ac)
dup 0 lt {
% No real roots
pop pop pop null
} {
sqrt % a b √(b²-4ac)
1 index neg % a b √d (-b)
1 index add % a b √d (-b+√d)
3 index 2 mul div % a b √d root1
4 1 roll % root1 a b √d
neg add % root1 a (-b-√d)
exch 2 mul div % root1 root2
} ifelse
} def
7. Edge Cases
10. Error Conditions
stackunderflow-
The operand stack is empty.
typecheck-
The operand is not a number.
rangecheck-
The operand is negative.
-4 sqrt % ERROR: rangecheck
11. See Also
-
Arithmetic and Math - All arithmetic operators