三平方の定理はMath.hypot・C言語でも使える
http://rubyist.g.hatena.ne.jp/kusakari/20081020/1224497314
Rubyで三平方の定理を使う場合はMath.hypotを使う。hypotはhypotenuse(斜辺)の略。見かけないんだけど、あんま知られてないのかな。組み込みなのにね。
Math.sqrt(3**2 + 4**2) # => 5.0 Math.hypot(3, 4) # => 5.0 Math.hypot(5, 12) # => 13.0
ちなみにソースはこんなの。
static VALUE math_hypot(obj, x, y) VALUE obj, x, y; { Need_Float2(x, y); return rb_float_new(hypot(RFLOAT(x)->value, RFLOAT(y)->value)); }
hypot関数はC言語でも使える。
#include <math.h> double hypot(double x, double y); float hypotf(float x, float y); long double hypotl (long double x, long double y); -lm でリンクする。
missing/hypot.cより。パブリックドメインなのでそのまま転載。
/* public domain rewrite of hypot */ #include <math.h> double hypot(x,y) double x, y; { if (x < 0) x = -x; if (y < 0) y = -y; if (x < y) { double tmp = x; x = y; y = tmp; } if (y == 0.0) return x; y /= x; return x * sqrt(1.0+y*y); }