50. Pow(x, n)#49
Conversation
| cpython pow: https://github.com/python/cpython/blob/4641925bf27d9ca09b88e3063a391931da3e7c0c/Objects/longobject.c#L4983 | ||
| - ValueError を出そうと思っていたが、pow 関数が "ZeroDivisionError: 0.0 cannot be raised to a negative power" を出していることに気づいた。 | ||
| - 0^-1 = 1/0 で ZeroDivisionError ですかね。ただし pow は x = 0 n = 1 で 1 を返している。問題の制約でこれものぞこう。 | ||
| - 以下では、0^0 = 1 と書かれている |
There was a problem hiding this comment.
数学では 0^0 を 1 としたほうが都合がいいことが多いので、そう定義することが多いですね。
There was a problem hiding this comment.
ありがとうございます。
他の言語でも pow(0, 0) で 1 を返すのかと思っていたら、そうでもないんですね。
https://en.cppreference.com/w/c/numeric/math/pow.html
If base is zero and exponent is zero, a domain error may occur.
https://en.cppreference.com/w/cpp/numeric/math/pow
If base is zero and exp is zero, a domain error may occur.
どうするかはよく話をしていこうと思います。
| pow: https://docs.python.org/3/library/functions.html#pow | ||
| cpython pow: https://github.com/python/cpython/blob/4641925bf27d9ca09b88e3063a391931da3e7c0c/Objects/longobject.c#L4983 | ||
| - ValueError を出そうと思っていたが、pow 関数が "ZeroDivisionError: 0.0 cannot be raised to a negative power" を出していることに気づいた。 | ||
| - 0^-1 = 1/0 で ZeroDivisionError ですかね。ただし pow は x = 0 n = 1 で 1 を返している。問題の制約でこれものぞこう。 |
There was a problem hiding this comment.
ただし pow は x = 0 n = 1 で 1 を返している。問題の制約でこれものぞこう。
問題の制約を見たとき、x = 0, n = 0 は不正な値として処理するものと思っていたが pow 関数では 1 を返している。
(typo しているのと、わかりにくい文章だったので修正)
| base *= base | ||
| exponent //= 2 | ||
| return result | ||
|
|
There was a problem hiding this comment.
このコードが読みやすかったです。
if n < 0: の中で指数の符号を反転させる方が自然に感じました。
L156-158において、n, x を使うか、base, exponent を使うかは微妙なところですが、私は後者かなと思いました。
There was a problem hiding this comment.
ありがとうございます。
そこについても悩んだところでした。x と n が使われている範囲を限定するということを考えると、おっしゃるように後者の方がよさそうに思いました。微妙なところかもしれませんが、自分の中では x と n の方が読みやすいかなと思った次第でした。(ここも時間を置くと考え変わるかもしれません。)
There was a problem hiding this comment.
自分だったら、最初の引数の情報は後からは使わないので、baseとexponentは定義せずにxとnをそのまま更新していってしまうかもしれないと思いました。
(というか、関数を呼び出す側のIDE補完とかの分かりやすさを考えると、本来は引数の名前がbaseとかexponentとかであるべきな気がします)
There was a problem hiding this comment.
ありがとうございます。
おっしゃるように自分で0から作るときは引数をどうするのかから考える必要がありますね。
| base = 1.0 / x | ||
| exponent = -n | ||
| while exponent > 0: | ||
| if exponent % 2 == 1: |
There was a problem hiding this comment.
自分も%で書きそうな気がしますが、exponent & 1とも書けると思いました。
こちらも参考にしてみてください。
potrue/leetcode#45 (comment)
There was a problem hiding this comment.
ありがとうございます。
& 1 は自分だと書かないかもしれないですが、読める必要はあると思うので参考にさせていただきます。
| if exponent % 2 == 1: | ||
| result *= base | ||
| base *= base | ||
| exponent //= 2 |
This Problem
https://leetcode.com/problems/powx-n/description/
Next Problem
https://leetcode.com/problems/k-th-symbol-in-grammar/