LoginSignup
1
0

More than 5 years have passed since last update.

対角線の長さを求める関数

Last updated at Posted at 2019-04-23

対角線の長さを求めることがあったのでメモ

コード

(a,b)=>Math.abs(a===b?Math.SQRT2*a:Math.sqrt(a**2+b**2))

追記

htsign様から便利な関数を教えていただきました。

Math.hypot 関数で求められます。

Math.hypot(3, 4); // ==> 5


MDN
Math​.hypot()

概要
引数の二乗和の平方根を返します。

https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Math/hypot


こんな関数があったとは。。

一応処理時間も測って見ました。

console.time("original");
((a,b)=>Math.abs(a===b?Math.SQRT2*a:Math.sqrt(a**2+b**2)))(3, 4);
console.timeEnd("original");
console.time("Math.hypot");
Math.hypot(3, 4);
console.timeEnd("Math.hypot");
Name Time
original 0.010009765625ms
Math.hypot 0.005126953125ms

は、早い。。。

またひとつ勉強になりました。

1
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0