| 7409 | |
| 7410 | def simplify_real(self): |
| 7411 | r""" |
| 7412 | Simplify the given expression over the real numbers. This allows |
| 7413 | the simplification of `\sqrt{x^{2}}` into `\left|x\\right|`. |
| 7414 | |
| 7415 | INPUT: |
| 7416 | |
| 7417 | - ``self`` -- the expression to convert. |
| 7418 | |
| 7419 | OUTPUT: |
| 7420 | |
| 7421 | A new expression, equivalent to the original one under the |
| 7422 | assumption that the variables involved are real. |
| 7423 | |
| 7424 | EXAMPLES:: |
| 7425 | |
| 7426 | sage: f = sqrt(x^2) |
| 7427 | sage: f.simplify_real() |
| 7428 | abs(x) |
| 7429 | |
| 7430 | TESTS: |
| 7431 | |
| 7432 | We set the Maxima ``domain`` variable to 'real' before we call |
| 7433 | out to Maxima. When we return, however, we should set the |
| 7434 | ``domain`` back to what it was, rather than assuming that it |
| 7435 | was 'complex'. |
| 7436 | |
| 7437 | sage: from sage.calculus.calculus import maxima |
| 7438 | sage: maxima('domain: real;') |
| 7439 | real |
| 7440 | sage: x.simplify_real() |
| 7441 | x |
| 7442 | sage: maxima('domain;') |
| 7443 | real |
| 7444 | sage: maxima('domain: complex;') |
| 7445 | complex |
| 7446 | |
| 7447 | We forget the assumptions that our variables are real after |
| 7448 | simplification; make sure we don't forget an assumption that |
| 7449 | existed before we were called:: |
| 7450 | |
| 7451 | sage: assume(x, 'real') |
| 7452 | sage: x.simplify_real() |
| 7453 | x |
| 7454 | sage: assumptions() |
| 7455 | [x is real] |
| 7456 | sage: forget() |
| 7457 | |
| 7458 | No new assumptions should exist after the call:: |
| 7459 | |
| 7460 | sage: assumptions() |
| 7461 | [] |
| 7462 | sage: x.simplify_real() |
| 7463 | x |
| 7464 | sage: assumptions() |
| 7465 | [] |
| 7466 | |
| 7467 | """ |
| 7468 | from sage.symbolic.assumptions import assume, assumptions, forget |
| 7469 | from sage.calculus.calculus import maxima |
| 7470 | original_domain = maxima.eval('domain') |
| 7471 | original_assumptions = assumptions() |
| 7472 | |
| 7473 | maxima.eval('domain: real$') |
| 7474 | |
| 7475 | # We might as well go all the way and tell Maxima to assume |
| 7476 | # that all variables are real. Since we're setting the |
| 7477 | # simplification domain (and it's indiscriminate), you'd |
| 7478 | # better not call this unless your variables really are real |
| 7479 | # anyway. |
| 7480 | for v in self.variables(): |
| 7481 | assume(v, 'real'); |
| 7482 | |
| 7483 | result = self.simplify(); |
| 7484 | |
| 7485 | # Set the domain back to what it was before we were called. |
| 7486 | maxima.eval('domain: %s$' % original_domain) |
| 7487 | |
| 7488 | # Forget all assumptions, and restore the ones that existed |
| 7489 | # when we were called. This is much simpler than the bookkeeping |
| 7490 | # necessary otherwise. |
| 7491 | forget() |
| 7492 | for assumption in original_assumptions: |
| 7493 | assume(assumption); |
| 7494 | |
| 7495 | return result |
| 7496 | |
| 7497 | |