LoginSignup
4
3

More than 5 years have passed since last update.

Sympyでsqrt(a**2)をaと表示する方法(a>0)

Last updated at Posted at 2018-01-10

はじめに

SympyというPythonの代数計算ライブラリ(http://www.sympy.org/ )がある。Woflram社のMathematicaと類似の計算を行うことが可能である。

このソフトウェアの関数のなかに、sqrt()という1/2乗を計算する関数があるのだが、素朴にsqrt(a**2)を打ち込むと

In [1]: import sympy
In [2]: from sympy import *
In [3]: a = symbols("a")
In [4]: sqrt(a**2)
Out[4]: sqrt(a**2)

と打ち込むと、根号がとれない。$a$の符号について事前知識があれば、とってほしい。それを行う方法についてのメモである。

環境について

  • Python
    • Python 3.6.2
  • Sympy
    • 1.1.1

Sympyでsqrt(a**2)をaと表示する方法(a>0)

「はじめに」にも書いたように$a$の符号に関する事前知識がないために根号がとれない。ドキュメントを読むと下記のように書いてある。つまり、少なくとも以下の3通りの方法がある。

  • 事前にシンボルに符号を指定しておく
  • powdenest()を使用して無理やり根号を外す

以下のドキュメント見れば終わりという感じもするが、せっかくなので日本語で書いておく。

Note that sqrt(x**2) does not simplify to x.

>> sqrt(x**2)
sqrt(x**2)

This is because the two are not equal to each other in general.
For example, consider x == -1:

>> from sympy import Eq
>> Eq(sqrt(x**2), x).subs(x, -1)
False

This is because sqrt computes the principal square root, so the square may
put the argument in a different branch. This identity does hold if x is
positive:

>> y = Symbol('y', positive=True)
>> sqrt(y**2)
y

You can force this simplification by using the powdenest() function with
the force option set to True:

>> from sympy import powdenest
>> sqrt(x**2)
sqrt(x**2)
>> powdenest(sqrt(x**2), force=True)
x

事前に符号を指定しておく方法

sqrtの中に入れる記号の符号を事前に指定する方法である。このためには、記号定義を行う際にpositive=Trueとして正とするか、negative=Trueとして負とする。

In [6]: a = symbols("a", positive=True)
In [7]: sqrt(a**2)
Out[7]: a

In [8]: a = symbols("a", negative=True)
In [9]: sqrt(a**2)
Out[9]: -a

たしかに根号がとれる。

powdenest()を使用する方法

次に少し危険そうな方法として、無理やり外す方法がある。

In [14]: a = symbols("a")

In [15]: powdenest(sqrt(a**2),force=True)
Out[15]: a

確かにあたかも$a>0$であるかのようにとれる。しかし、

In [19]: powdenest(sqrt(a**2),force=True).subs([(a,-1)])
Out[19]: -1

となってしまうので注意が必要である。

4
3
0

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
4
3