0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Rubyでべき乗の計算をする2つの方法

Posted at

はじめに

Rubyでべき乗の計算をする場面に遭遇しました。

初歩的ですがやり方を忘れていたため、備忘録としてまとめます。

Rubyのバージョンは次のとおりです。

$ ruby -v
ruby 3.3.4 (2024-07-09 revision be1089c8ec) [arm64-darwin22]

Rubyでべき乗の計算をする2つの方法

次の2つのやり方がありました。

  1. 算術演算子**を使う
  2. powメソッドを使う

1. 算術演算子**を使う

1つ目は算術演算子**を使う方法です。

次のように使用します。

irb(main):001> 2 ** 3
=> 8
irb(main):002> 3 ** 4
=> 81
irb(main):003> 2 ** (-2)
=> (1/4)  # Rational型が返される
irb(main):004> 2.0 ** (-2)
=> 0.25   # Float型が返される

2. powメソッドを使う

2つ目はIntegerクラスのpowメソッドを使う方法です。

次のように使用します。

irb(main):001> 2.pow(3)
=> 8
irb(main):002> 3.pow(4)
=> 81
irb(main):003> 2.pow(-2)
=> (1/4)  # Rational型が返される
irb(main):004> 2.0.pow(-2)
(irb):4:in `<main>': undefined method `pow' for an instance of Float (NoMethodError)

2.0.pow(-2)
   ^^^^
        from <internal:kernel>:187:in `loop'
        from /opt/homebrew/lib/ruby/gems/3.3.0/gems/irb-1.14.1/exe/irb:9:in `<top (required)>'
        from /opt/homebrew/lib/ruby/gems/3.3.0/bin/irb:25:in `load'
        from /opt/homebrew/lib/ruby/gems/3.3.0/bin/irb:25:in `<main>'
irb(main):004> (2.0).pow(-2)
(irb):4:in `<main>': undefined method `pow' for an instance of Float (NoMethodError)

(2.0).pow(-2)
     ^^^^
        from <internal:kernel>:187:in `loop'
        from /opt/homebrew/lib/ruby/gems/3.3.0/gems/irb-1.14.1/exe/irb:9:in `<top (required)>'
        from /opt/homebrew/lib/ruby/gems/3.3.0/bin/irb:25:in `load'
        from /opt/homebrew/lib/ruby/gems/3.3.0/bin/irb:25:in `<main>'

powメソッドの場合、(2.0).pow(-2)とFloat型に対して実行するとエラーになります。

おわりに

初歩的な内容でも、自分がうろ覚えなものであれば気にせずアウトプットしていきます。

参考

0
0
1

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?