v / vlib / math / hypot.v
27 lines · 26 sloc · 469 bytes · 3e331d4cf0b05f1983e760e397a400456ead9e4b
Raw
1module math
2
3// hypot returns the hypotenuse of the triangle give two sides.
4//
5// special cases are:
6// hypot(±inf, y) = +inf
7// hypot(x, ±inf) = +inf
8// hypot(nan, y) = nan
9// hypot(x, nan) = nan
10pub fn hypot(x f64, y f64) f64 {
11 mut p := abs(x)
12 mut q := abs(y)
13 if is_inf(p, 1) || is_inf(q, 1) {
14 return inf(1)
15 }
16 if is_nan(p) || is_nan(q) {
17 return nan()
18 }
19 if p < q {
20 p, q = q, p
21 }
22 if p == 0.0 {
23 return 0.0
24 }
25 q = q / p
26 return p * sqrt(1 + q * q)
27}
28