Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .gitattributes +3 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/calculus/__pycache__/__init__.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/calculus/__pycache__/accumulationbounds.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/calculus/__pycache__/euler.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/calculus/__pycache__/finite_diff.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/calculus/__pycache__/singularities.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/calculus/__pycache__/util.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/calculus/accumulationbounds.py +804 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/calculus/finite_diff.py +476 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/calculus/tests/__init__.py +0 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/calculus/tests/__pycache__/__init__.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/calculus/tests/__pycache__/test_accumulationbounds.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/calculus/tests/__pycache__/test_euler.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/calculus/tests/__pycache__/test_finite_diff.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/calculus/tests/__pycache__/test_singularities.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/calculus/tests/__pycache__/test_util.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/calculus/tests/test_accumulationbounds.py +336 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/calculus/tests/test_euler.py +74 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/calculus/tests/test_finite_diff.py +168 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/calculus/tests/test_singularities.py +122 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/calculus/tests/test_util.py +392 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/calculus/util.py +905 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/core/__pycache__/expr.cpython-310.pyc +3 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/core/__pycache__/function.cpython-310.pyc +3 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/__init__.py +67 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/__pycache__/__init__.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/__pycache__/digits.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/__pycache__/elliptic_curve.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/__pycache__/generate.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/__pycache__/primetest.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/__pycache__/qs.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/bbp_pi.py +190 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/continued_fraction.py +369 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/egyptian_fraction.py +223 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/elliptic_curve.py +397 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/factor_.py +2668 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/modular.py +291 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/multinomial.py +188 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/partitions_.py +278 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_bbp_pi.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_continued_fraction.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_ecm.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_generate.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_hypothesis.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_modular.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_multinomial.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_partitions.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_primetest.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_qs.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/tests/test_continued_fraction.py +77 -0
.gitattributes
CHANGED
|
@@ -872,3 +872,6 @@ infer_4_47_1/lib/python3.10/site-packages/sympy/matrices/__pycache__/matrixbase.
|
|
| 872 |
infer_4_47_1/lib/python3.10/site-packages/sympy/matrices/tests/__pycache__/test_matrixbase.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 873 |
infer_4_47_1/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/perm_groups.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 874 |
infer_4_47_1/lib/python3.10/site-packages/sympy/core/tests/__pycache__/test_args.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
| 872 |
infer_4_47_1/lib/python3.10/site-packages/sympy/matrices/tests/__pycache__/test_matrixbase.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 873 |
infer_4_47_1/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/perm_groups.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 874 |
infer_4_47_1/lib/python3.10/site-packages/sympy/core/tests/__pycache__/test_args.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 875 |
+
infer_4_47_1/lib/python3.10/site-packages/sympy/stats/__pycache__/crv_types.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 876 |
+
infer_4_47_1/lib/python3.10/site-packages/sympy/core/__pycache__/function.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 877 |
+
infer_4_47_1/lib/python3.10/site-packages/sympy/core/__pycache__/expr.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
infer_4_47_1/lib/python3.10/site-packages/sympy/calculus/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (853 Bytes). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/sympy/calculus/__pycache__/accumulationbounds.cpython-310.pyc
ADDED
|
Binary file (20.6 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/sympy/calculus/__pycache__/euler.cpython-310.pyc
ADDED
|
Binary file (3.81 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/sympy/calculus/__pycache__/finite_diff.cpython-310.pyc
ADDED
|
Binary file (17.3 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/sympy/calculus/__pycache__/singularities.cpython-310.pyc
ADDED
|
Binary file (12.2 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/sympy/calculus/__pycache__/util.cpython-310.pyc
ADDED
|
Binary file (23.9 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/sympy/calculus/accumulationbounds.py
ADDED
|
@@ -0,0 +1,804 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.core import Add, Mul, Pow, S
|
| 2 |
+
from sympy.core.basic import Basic
|
| 3 |
+
from sympy.core.expr import Expr
|
| 4 |
+
from sympy.core.numbers import _sympifyit, oo, zoo
|
| 5 |
+
from sympy.core.relational import is_le, is_lt, is_ge, is_gt
|
| 6 |
+
from sympy.core.sympify import _sympify
|
| 7 |
+
from sympy.functions.elementary.miscellaneous import Min, Max
|
| 8 |
+
from sympy.logic.boolalg import And
|
| 9 |
+
from sympy.multipledispatch import dispatch
|
| 10 |
+
from sympy.series.order import Order
|
| 11 |
+
from sympy.sets.sets import FiniteSet
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class AccumulationBounds(Expr):
|
| 15 |
+
r"""An accumulation bounds.
|
| 16 |
+
|
| 17 |
+
# Note AccumulationBounds has an alias: AccumBounds
|
| 18 |
+
|
| 19 |
+
AccumulationBounds represent an interval `[a, b]`, which is always closed
|
| 20 |
+
at the ends. Here `a` and `b` can be any value from extended real numbers.
|
| 21 |
+
|
| 22 |
+
The intended meaning of AccummulationBounds is to give an approximate
|
| 23 |
+
location of the accumulation points of a real function at a limit point.
|
| 24 |
+
|
| 25 |
+
Let `a` and `b` be reals such that `a \le b`.
|
| 26 |
+
|
| 27 |
+
`\left\langle a, b\right\rangle = \{x \in \mathbb{R} \mid a \le x \le b\}`
|
| 28 |
+
|
| 29 |
+
`\left\langle -\infty, b\right\rangle = \{x \in \mathbb{R} \mid x \le b\} \cup \{-\infty, \infty\}`
|
| 30 |
+
|
| 31 |
+
`\left\langle a, \infty \right\rangle = \{x \in \mathbb{R} \mid a \le x\} \cup \{-\infty, \infty\}`
|
| 32 |
+
|
| 33 |
+
`\left\langle -\infty, \infty \right\rangle = \mathbb{R} \cup \{-\infty, \infty\}`
|
| 34 |
+
|
| 35 |
+
``oo`` and ``-oo`` are added to the second and third definition respectively,
|
| 36 |
+
since if either ``-oo`` or ``oo`` is an argument, then the other one should
|
| 37 |
+
be included (though not as an end point). This is forced, since we have,
|
| 38 |
+
for example, ``1/AccumBounds(0, 1) = AccumBounds(1, oo)``, and the limit at
|
| 39 |
+
`0` is not one-sided. As `x` tends to `0-`, then `1/x \rightarrow -\infty`, so `-\infty`
|
| 40 |
+
should be interpreted as belonging to ``AccumBounds(1, oo)`` though it need
|
| 41 |
+
not appear explicitly.
|
| 42 |
+
|
| 43 |
+
In many cases it suffices to know that the limit set is bounded.
|
| 44 |
+
However, in some other cases more exact information could be useful.
|
| 45 |
+
For example, all accumulation values of `\cos(x) + 1` are non-negative.
|
| 46 |
+
(``AccumBounds(-1, 1) + 1 = AccumBounds(0, 2)``)
|
| 47 |
+
|
| 48 |
+
A AccumulationBounds object is defined to be real AccumulationBounds,
|
| 49 |
+
if its end points are finite reals.
|
| 50 |
+
|
| 51 |
+
Let `X`, `Y` be real AccumulationBounds, then their sum, difference,
|
| 52 |
+
product are defined to be the following sets:
|
| 53 |
+
|
| 54 |
+
`X + Y = \{ x+y \mid x \in X \cap y \in Y\}`
|
| 55 |
+
|
| 56 |
+
`X - Y = \{ x-y \mid x \in X \cap y \in Y\}`
|
| 57 |
+
|
| 58 |
+
`X \times Y = \{ x \times y \mid x \in X \cap y \in Y\}`
|
| 59 |
+
|
| 60 |
+
When an AccumBounds is raised to a negative power, if 0 is contained
|
| 61 |
+
between the bounds then an infinite range is returned, otherwise if an
|
| 62 |
+
endpoint is 0 then a semi-infinite range with consistent sign will be returned.
|
| 63 |
+
|
| 64 |
+
AccumBounds in expressions behave a lot like Intervals but the
|
| 65 |
+
semantics are not necessarily the same. Division (or exponentiation
|
| 66 |
+
to a negative integer power) could be handled with *intervals* by
|
| 67 |
+
returning a union of the results obtained after splitting the
|
| 68 |
+
bounds between negatives and positives, but that is not done with
|
| 69 |
+
AccumBounds. In addition, bounds are assumed to be independent of
|
| 70 |
+
each other; if the same bound is used in more than one place in an
|
| 71 |
+
expression, the result may not be the supremum or infimum of the
|
| 72 |
+
expression (see below). Finally, when a boundary is ``1``,
|
| 73 |
+
exponentiation to the power of ``oo`` yields ``oo``, neither
|
| 74 |
+
``1`` nor ``nan``.
|
| 75 |
+
|
| 76 |
+
Examples
|
| 77 |
+
========
|
| 78 |
+
|
| 79 |
+
>>> from sympy import AccumBounds, sin, exp, log, pi, E, S, oo
|
| 80 |
+
>>> from sympy.abc import x
|
| 81 |
+
|
| 82 |
+
>>> AccumBounds(0, 1) + AccumBounds(1, 2)
|
| 83 |
+
AccumBounds(1, 3)
|
| 84 |
+
|
| 85 |
+
>>> AccumBounds(0, 1) - AccumBounds(0, 2)
|
| 86 |
+
AccumBounds(-2, 1)
|
| 87 |
+
|
| 88 |
+
>>> AccumBounds(-2, 3)*AccumBounds(-1, 1)
|
| 89 |
+
AccumBounds(-3, 3)
|
| 90 |
+
|
| 91 |
+
>>> AccumBounds(1, 2)*AccumBounds(3, 5)
|
| 92 |
+
AccumBounds(3, 10)
|
| 93 |
+
|
| 94 |
+
The exponentiation of AccumulationBounds is defined
|
| 95 |
+
as follows:
|
| 96 |
+
|
| 97 |
+
If 0 does not belong to `X` or `n > 0` then
|
| 98 |
+
|
| 99 |
+
`X^n = \{ x^n \mid x \in X\}`
|
| 100 |
+
|
| 101 |
+
>>> AccumBounds(1, 4)**(S(1)/2)
|
| 102 |
+
AccumBounds(1, 2)
|
| 103 |
+
|
| 104 |
+
otherwise, an infinite or semi-infinite result is obtained:
|
| 105 |
+
|
| 106 |
+
>>> 1/AccumBounds(-1, 1)
|
| 107 |
+
AccumBounds(-oo, oo)
|
| 108 |
+
>>> 1/AccumBounds(0, 2)
|
| 109 |
+
AccumBounds(1/2, oo)
|
| 110 |
+
>>> 1/AccumBounds(-oo, 0)
|
| 111 |
+
AccumBounds(-oo, 0)
|
| 112 |
+
|
| 113 |
+
A boundary of 1 will always generate all nonnegatives:
|
| 114 |
+
|
| 115 |
+
>>> AccumBounds(1, 2)**oo
|
| 116 |
+
AccumBounds(0, oo)
|
| 117 |
+
>>> AccumBounds(0, 1)**oo
|
| 118 |
+
AccumBounds(0, oo)
|
| 119 |
+
|
| 120 |
+
If the exponent is itself an AccumulationBounds or is not an
|
| 121 |
+
integer then unevaluated results will be returned unless the base
|
| 122 |
+
values are positive:
|
| 123 |
+
|
| 124 |
+
>>> AccumBounds(2, 3)**AccumBounds(-1, 2)
|
| 125 |
+
AccumBounds(1/3, 9)
|
| 126 |
+
>>> AccumBounds(-2, 3)**AccumBounds(-1, 2)
|
| 127 |
+
AccumBounds(-2, 3)**AccumBounds(-1, 2)
|
| 128 |
+
|
| 129 |
+
>>> AccumBounds(-2, -1)**(S(1)/2)
|
| 130 |
+
sqrt(AccumBounds(-2, -1))
|
| 131 |
+
|
| 132 |
+
Note: `\left\langle a, b\right\rangle^2` is not same as `\left\langle a, b\right\rangle \times \left\langle a, b\right\rangle`
|
| 133 |
+
|
| 134 |
+
>>> AccumBounds(-1, 1)**2
|
| 135 |
+
AccumBounds(0, 1)
|
| 136 |
+
|
| 137 |
+
>>> AccumBounds(1, 3) < 4
|
| 138 |
+
True
|
| 139 |
+
|
| 140 |
+
>>> AccumBounds(1, 3) < -1
|
| 141 |
+
False
|
| 142 |
+
|
| 143 |
+
Some elementary functions can also take AccumulationBounds as input.
|
| 144 |
+
A function `f` evaluated for some real AccumulationBounds `\left\langle a, b \right\rangle`
|
| 145 |
+
is defined as `f(\left\langle a, b\right\rangle) = \{ f(x) \mid a \le x \le b \}`
|
| 146 |
+
|
| 147 |
+
>>> sin(AccumBounds(pi/6, pi/3))
|
| 148 |
+
AccumBounds(1/2, sqrt(3)/2)
|
| 149 |
+
|
| 150 |
+
>>> exp(AccumBounds(0, 1))
|
| 151 |
+
AccumBounds(1, E)
|
| 152 |
+
|
| 153 |
+
>>> log(AccumBounds(1, E))
|
| 154 |
+
AccumBounds(0, 1)
|
| 155 |
+
|
| 156 |
+
Some symbol in an expression can be substituted for a AccumulationBounds
|
| 157 |
+
object. But it does not necessarily evaluate the AccumulationBounds for
|
| 158 |
+
that expression.
|
| 159 |
+
|
| 160 |
+
The same expression can be evaluated to different values depending upon
|
| 161 |
+
the form it is used for substitution since each instance of an
|
| 162 |
+
AccumulationBounds is considered independent. For example:
|
| 163 |
+
|
| 164 |
+
>>> (x**2 + 2*x + 1).subs(x, AccumBounds(-1, 1))
|
| 165 |
+
AccumBounds(-1, 4)
|
| 166 |
+
|
| 167 |
+
>>> ((x + 1)**2).subs(x, AccumBounds(-1, 1))
|
| 168 |
+
AccumBounds(0, 4)
|
| 169 |
+
|
| 170 |
+
References
|
| 171 |
+
==========
|
| 172 |
+
|
| 173 |
+
.. [1] https://en.wikipedia.org/wiki/Interval_arithmetic
|
| 174 |
+
|
| 175 |
+
.. [2] https://fab.cba.mit.edu/classes/S62.12/docs/Hickey_interval.pdf
|
| 176 |
+
|
| 177 |
+
Notes
|
| 178 |
+
=====
|
| 179 |
+
|
| 180 |
+
Do not use ``AccumulationBounds`` for floating point interval arithmetic
|
| 181 |
+
calculations, use ``mpmath.iv`` instead.
|
| 182 |
+
"""
|
| 183 |
+
|
| 184 |
+
is_extended_real = True
|
| 185 |
+
is_number = False
|
| 186 |
+
|
| 187 |
+
def __new__(cls, min, max):
|
| 188 |
+
|
| 189 |
+
min = _sympify(min)
|
| 190 |
+
max = _sympify(max)
|
| 191 |
+
|
| 192 |
+
# Only allow real intervals (use symbols with 'is_extended_real=True').
|
| 193 |
+
if not min.is_extended_real or not max.is_extended_real:
|
| 194 |
+
raise ValueError("Only real AccumulationBounds are supported")
|
| 195 |
+
|
| 196 |
+
if max == min:
|
| 197 |
+
return max
|
| 198 |
+
|
| 199 |
+
# Make sure that the created AccumBounds object will be valid.
|
| 200 |
+
if max.is_number and min.is_number:
|
| 201 |
+
bad = max.is_comparable and min.is_comparable and max < min
|
| 202 |
+
else:
|
| 203 |
+
bad = (max - min).is_extended_negative
|
| 204 |
+
if bad:
|
| 205 |
+
raise ValueError(
|
| 206 |
+
"Lower limit should be smaller than upper limit")
|
| 207 |
+
|
| 208 |
+
return Basic.__new__(cls, min, max)
|
| 209 |
+
|
| 210 |
+
# setting the operation priority
|
| 211 |
+
_op_priority = 11.0
|
| 212 |
+
|
| 213 |
+
def _eval_is_real(self):
|
| 214 |
+
if self.min.is_real and self.max.is_real:
|
| 215 |
+
return True
|
| 216 |
+
|
| 217 |
+
@property
|
| 218 |
+
def min(self):
|
| 219 |
+
"""
|
| 220 |
+
Returns the minimum possible value attained by AccumulationBounds
|
| 221 |
+
object.
|
| 222 |
+
|
| 223 |
+
Examples
|
| 224 |
+
========
|
| 225 |
+
|
| 226 |
+
>>> from sympy import AccumBounds
|
| 227 |
+
>>> AccumBounds(1, 3).min
|
| 228 |
+
1
|
| 229 |
+
|
| 230 |
+
"""
|
| 231 |
+
return self.args[0]
|
| 232 |
+
|
| 233 |
+
@property
|
| 234 |
+
def max(self):
|
| 235 |
+
"""
|
| 236 |
+
Returns the maximum possible value attained by AccumulationBounds
|
| 237 |
+
object.
|
| 238 |
+
|
| 239 |
+
Examples
|
| 240 |
+
========
|
| 241 |
+
|
| 242 |
+
>>> from sympy import AccumBounds
|
| 243 |
+
>>> AccumBounds(1, 3).max
|
| 244 |
+
3
|
| 245 |
+
|
| 246 |
+
"""
|
| 247 |
+
return self.args[1]
|
| 248 |
+
|
| 249 |
+
@property
|
| 250 |
+
def delta(self):
|
| 251 |
+
"""
|
| 252 |
+
Returns the difference of maximum possible value attained by
|
| 253 |
+
AccumulationBounds object and minimum possible value attained
|
| 254 |
+
by AccumulationBounds object.
|
| 255 |
+
|
| 256 |
+
Examples
|
| 257 |
+
========
|
| 258 |
+
|
| 259 |
+
>>> from sympy import AccumBounds
|
| 260 |
+
>>> AccumBounds(1, 3).delta
|
| 261 |
+
2
|
| 262 |
+
|
| 263 |
+
"""
|
| 264 |
+
return self.max - self.min
|
| 265 |
+
|
| 266 |
+
@property
|
| 267 |
+
def mid(self):
|
| 268 |
+
"""
|
| 269 |
+
Returns the mean of maximum possible value attained by
|
| 270 |
+
AccumulationBounds object and minimum possible value
|
| 271 |
+
attained by AccumulationBounds object.
|
| 272 |
+
|
| 273 |
+
Examples
|
| 274 |
+
========
|
| 275 |
+
|
| 276 |
+
>>> from sympy import AccumBounds
|
| 277 |
+
>>> AccumBounds(1, 3).mid
|
| 278 |
+
2
|
| 279 |
+
|
| 280 |
+
"""
|
| 281 |
+
return (self.min + self.max) / 2
|
| 282 |
+
|
| 283 |
+
@_sympifyit('other', NotImplemented)
|
| 284 |
+
def _eval_power(self, other):
|
| 285 |
+
return self.__pow__(other)
|
| 286 |
+
|
| 287 |
+
@_sympifyit('other', NotImplemented)
|
| 288 |
+
def __add__(self, other):
|
| 289 |
+
if isinstance(other, Expr):
|
| 290 |
+
if isinstance(other, AccumBounds):
|
| 291 |
+
return AccumBounds(
|
| 292 |
+
Add(self.min, other.min),
|
| 293 |
+
Add(self.max, other.max))
|
| 294 |
+
if other is S.Infinity and self.min is S.NegativeInfinity or \
|
| 295 |
+
other is S.NegativeInfinity and self.max is S.Infinity:
|
| 296 |
+
return AccumBounds(-oo, oo)
|
| 297 |
+
elif other.is_extended_real:
|
| 298 |
+
if self.min is S.NegativeInfinity and self.max is S.Infinity:
|
| 299 |
+
return AccumBounds(-oo, oo)
|
| 300 |
+
elif self.min is S.NegativeInfinity:
|
| 301 |
+
return AccumBounds(-oo, self.max + other)
|
| 302 |
+
elif self.max is S.Infinity:
|
| 303 |
+
return AccumBounds(self.min + other, oo)
|
| 304 |
+
else:
|
| 305 |
+
return AccumBounds(Add(self.min, other), Add(self.max, other))
|
| 306 |
+
return Add(self, other, evaluate=False)
|
| 307 |
+
return NotImplemented
|
| 308 |
+
|
| 309 |
+
__radd__ = __add__
|
| 310 |
+
|
| 311 |
+
def __neg__(self):
|
| 312 |
+
return AccumBounds(-self.max, -self.min)
|
| 313 |
+
|
| 314 |
+
@_sympifyit('other', NotImplemented)
|
| 315 |
+
def __sub__(self, other):
|
| 316 |
+
if isinstance(other, Expr):
|
| 317 |
+
if isinstance(other, AccumBounds):
|
| 318 |
+
return AccumBounds(
|
| 319 |
+
Add(self.min, -other.max),
|
| 320 |
+
Add(self.max, -other.min))
|
| 321 |
+
if other is S.NegativeInfinity and self.min is S.NegativeInfinity or \
|
| 322 |
+
other is S.Infinity and self.max is S.Infinity:
|
| 323 |
+
return AccumBounds(-oo, oo)
|
| 324 |
+
elif other.is_extended_real:
|
| 325 |
+
if self.min is S.NegativeInfinity and self.max is S.Infinity:
|
| 326 |
+
return AccumBounds(-oo, oo)
|
| 327 |
+
elif self.min is S.NegativeInfinity:
|
| 328 |
+
return AccumBounds(-oo, self.max - other)
|
| 329 |
+
elif self.max is S.Infinity:
|
| 330 |
+
return AccumBounds(self.min - other, oo)
|
| 331 |
+
else:
|
| 332 |
+
return AccumBounds(
|
| 333 |
+
Add(self.min, -other),
|
| 334 |
+
Add(self.max, -other))
|
| 335 |
+
return Add(self, -other, evaluate=False)
|
| 336 |
+
return NotImplemented
|
| 337 |
+
|
| 338 |
+
@_sympifyit('other', NotImplemented)
|
| 339 |
+
def __rsub__(self, other):
|
| 340 |
+
return self.__neg__() + other
|
| 341 |
+
|
| 342 |
+
@_sympifyit('other', NotImplemented)
|
| 343 |
+
def __mul__(self, other):
|
| 344 |
+
if self.args == (-oo, oo):
|
| 345 |
+
return self
|
| 346 |
+
if isinstance(other, Expr):
|
| 347 |
+
if isinstance(other, AccumBounds):
|
| 348 |
+
if other.args == (-oo, oo):
|
| 349 |
+
return other
|
| 350 |
+
v = set()
|
| 351 |
+
for a in self.args:
|
| 352 |
+
vi = other*a
|
| 353 |
+
v.update(vi.args or (vi,))
|
| 354 |
+
return AccumBounds(Min(*v), Max(*v))
|
| 355 |
+
if other is S.Infinity:
|
| 356 |
+
if self.min.is_zero:
|
| 357 |
+
return AccumBounds(0, oo)
|
| 358 |
+
if self.max.is_zero:
|
| 359 |
+
return AccumBounds(-oo, 0)
|
| 360 |
+
if other is S.NegativeInfinity:
|
| 361 |
+
if self.min.is_zero:
|
| 362 |
+
return AccumBounds(-oo, 0)
|
| 363 |
+
if self.max.is_zero:
|
| 364 |
+
return AccumBounds(0, oo)
|
| 365 |
+
if other.is_extended_real:
|
| 366 |
+
if other.is_zero:
|
| 367 |
+
if self.max is S.Infinity:
|
| 368 |
+
return AccumBounds(0, oo)
|
| 369 |
+
if self.min is S.NegativeInfinity:
|
| 370 |
+
return AccumBounds(-oo, 0)
|
| 371 |
+
return S.Zero
|
| 372 |
+
if other.is_extended_positive:
|
| 373 |
+
return AccumBounds(
|
| 374 |
+
Mul(self.min, other),
|
| 375 |
+
Mul(self.max, other))
|
| 376 |
+
elif other.is_extended_negative:
|
| 377 |
+
return AccumBounds(
|
| 378 |
+
Mul(self.max, other),
|
| 379 |
+
Mul(self.min, other))
|
| 380 |
+
if isinstance(other, Order):
|
| 381 |
+
return other
|
| 382 |
+
return Mul(self, other, evaluate=False)
|
| 383 |
+
return NotImplemented
|
| 384 |
+
|
| 385 |
+
__rmul__ = __mul__
|
| 386 |
+
|
| 387 |
+
@_sympifyit('other', NotImplemented)
|
| 388 |
+
def __truediv__(self, other):
|
| 389 |
+
if isinstance(other, Expr):
|
| 390 |
+
if isinstance(other, AccumBounds):
|
| 391 |
+
if other.min.is_positive or other.max.is_negative:
|
| 392 |
+
return self * AccumBounds(1/other.max, 1/other.min)
|
| 393 |
+
|
| 394 |
+
if (self.min.is_extended_nonpositive and self.max.is_extended_nonnegative and
|
| 395 |
+
other.min.is_extended_nonpositive and other.max.is_extended_nonnegative):
|
| 396 |
+
if self.min.is_zero and other.min.is_zero:
|
| 397 |
+
return AccumBounds(0, oo)
|
| 398 |
+
if self.max.is_zero and other.min.is_zero:
|
| 399 |
+
return AccumBounds(-oo, 0)
|
| 400 |
+
return AccumBounds(-oo, oo)
|
| 401 |
+
|
| 402 |
+
if self.max.is_extended_negative:
|
| 403 |
+
if other.min.is_extended_negative:
|
| 404 |
+
if other.max.is_zero:
|
| 405 |
+
return AccumBounds(self.max / other.min, oo)
|
| 406 |
+
if other.max.is_extended_positive:
|
| 407 |
+
# if we were dealing with intervals we would return
|
| 408 |
+
# Union(Interval(-oo, self.max/other.max),
|
| 409 |
+
# Interval(self.max/other.min, oo))
|
| 410 |
+
return AccumBounds(-oo, oo)
|
| 411 |
+
|
| 412 |
+
if other.min.is_zero and other.max.is_extended_positive:
|
| 413 |
+
return AccumBounds(-oo, self.max / other.max)
|
| 414 |
+
|
| 415 |
+
if self.min.is_extended_positive:
|
| 416 |
+
if other.min.is_extended_negative:
|
| 417 |
+
if other.max.is_zero:
|
| 418 |
+
return AccumBounds(-oo, self.min / other.min)
|
| 419 |
+
if other.max.is_extended_positive:
|
| 420 |
+
# if we were dealing with intervals we would return
|
| 421 |
+
# Union(Interval(-oo, self.min/other.min),
|
| 422 |
+
# Interval(self.min/other.max, oo))
|
| 423 |
+
return AccumBounds(-oo, oo)
|
| 424 |
+
|
| 425 |
+
if other.min.is_zero and other.max.is_extended_positive:
|
| 426 |
+
return AccumBounds(self.min / other.max, oo)
|
| 427 |
+
|
| 428 |
+
elif other.is_extended_real:
|
| 429 |
+
if other in (S.Infinity, S.NegativeInfinity):
|
| 430 |
+
if self == AccumBounds(-oo, oo):
|
| 431 |
+
return AccumBounds(-oo, oo)
|
| 432 |
+
if self.max is S.Infinity:
|
| 433 |
+
return AccumBounds(Min(0, other), Max(0, other))
|
| 434 |
+
if self.min is S.NegativeInfinity:
|
| 435 |
+
return AccumBounds(Min(0, -other), Max(0, -other))
|
| 436 |
+
if other.is_extended_positive:
|
| 437 |
+
return AccumBounds(self.min / other, self.max / other)
|
| 438 |
+
elif other.is_extended_negative:
|
| 439 |
+
return AccumBounds(self.max / other, self.min / other)
|
| 440 |
+
if (1 / other) is S.ComplexInfinity:
|
| 441 |
+
return Mul(self, 1 / other, evaluate=False)
|
| 442 |
+
else:
|
| 443 |
+
return Mul(self, 1 / other)
|
| 444 |
+
|
| 445 |
+
return NotImplemented
|
| 446 |
+
|
| 447 |
+
@_sympifyit('other', NotImplemented)
|
| 448 |
+
def __rtruediv__(self, other):
|
| 449 |
+
if isinstance(other, Expr):
|
| 450 |
+
if other.is_extended_real:
|
| 451 |
+
if other.is_zero:
|
| 452 |
+
return S.Zero
|
| 453 |
+
if (self.min.is_extended_nonpositive and self.max.is_extended_nonnegative):
|
| 454 |
+
if self.min.is_zero:
|
| 455 |
+
if other.is_extended_positive:
|
| 456 |
+
return AccumBounds(Mul(other, 1 / self.max), oo)
|
| 457 |
+
if other.is_extended_negative:
|
| 458 |
+
return AccumBounds(-oo, Mul(other, 1 / self.max))
|
| 459 |
+
if self.max.is_zero:
|
| 460 |
+
if other.is_extended_positive:
|
| 461 |
+
return AccumBounds(-oo, Mul(other, 1 / self.min))
|
| 462 |
+
if other.is_extended_negative:
|
| 463 |
+
return AccumBounds(Mul(other, 1 / self.min), oo)
|
| 464 |
+
return AccumBounds(-oo, oo)
|
| 465 |
+
else:
|
| 466 |
+
return AccumBounds(Min(other / self.min, other / self.max),
|
| 467 |
+
Max(other / self.min, other / self.max))
|
| 468 |
+
return Mul(other, 1 / self, evaluate=False)
|
| 469 |
+
else:
|
| 470 |
+
return NotImplemented
|
| 471 |
+
|
| 472 |
+
@_sympifyit('other', NotImplemented)
|
| 473 |
+
def __pow__(self, other):
|
| 474 |
+
if isinstance(other, Expr):
|
| 475 |
+
if other is S.Infinity:
|
| 476 |
+
if self.min.is_extended_nonnegative:
|
| 477 |
+
if self.max < 1:
|
| 478 |
+
return S.Zero
|
| 479 |
+
if self.min > 1:
|
| 480 |
+
return S.Infinity
|
| 481 |
+
return AccumBounds(0, oo)
|
| 482 |
+
elif self.max.is_extended_negative:
|
| 483 |
+
if self.min > -1:
|
| 484 |
+
return S.Zero
|
| 485 |
+
if self.max < -1:
|
| 486 |
+
return zoo
|
| 487 |
+
return S.NaN
|
| 488 |
+
else:
|
| 489 |
+
if self.min > -1:
|
| 490 |
+
if self.max < 1:
|
| 491 |
+
return S.Zero
|
| 492 |
+
return AccumBounds(0, oo)
|
| 493 |
+
return AccumBounds(-oo, oo)
|
| 494 |
+
|
| 495 |
+
if other is S.NegativeInfinity:
|
| 496 |
+
return (1/self)**oo
|
| 497 |
+
|
| 498 |
+
# generically true
|
| 499 |
+
if (self.max - self.min).is_nonnegative:
|
| 500 |
+
# well defined
|
| 501 |
+
if self.min.is_nonnegative:
|
| 502 |
+
# no 0 to worry about
|
| 503 |
+
if other.is_nonnegative:
|
| 504 |
+
# no infinity to worry about
|
| 505 |
+
return self.func(self.min**other, self.max**other)
|
| 506 |
+
|
| 507 |
+
if other.is_zero:
|
| 508 |
+
return S.One # x**0 = 1
|
| 509 |
+
|
| 510 |
+
if other.is_Integer or other.is_integer:
|
| 511 |
+
if self.min.is_extended_positive:
|
| 512 |
+
return AccumBounds(
|
| 513 |
+
Min(self.min**other, self.max**other),
|
| 514 |
+
Max(self.min**other, self.max**other))
|
| 515 |
+
elif self.max.is_extended_negative:
|
| 516 |
+
return AccumBounds(
|
| 517 |
+
Min(self.max**other, self.min**other),
|
| 518 |
+
Max(self.max**other, self.min**other))
|
| 519 |
+
|
| 520 |
+
if other % 2 == 0:
|
| 521 |
+
if other.is_extended_negative:
|
| 522 |
+
if self.min.is_zero:
|
| 523 |
+
return AccumBounds(self.max**other, oo)
|
| 524 |
+
if self.max.is_zero:
|
| 525 |
+
return AccumBounds(self.min**other, oo)
|
| 526 |
+
return (1/self)**(-other)
|
| 527 |
+
return AccumBounds(
|
| 528 |
+
S.Zero, Max(self.min**other, self.max**other))
|
| 529 |
+
elif other % 2 == 1:
|
| 530 |
+
if other.is_extended_negative:
|
| 531 |
+
if self.min.is_zero:
|
| 532 |
+
return AccumBounds(self.max**other, oo)
|
| 533 |
+
if self.max.is_zero:
|
| 534 |
+
return AccumBounds(-oo, self.min**other)
|
| 535 |
+
return (1/self)**(-other)
|
| 536 |
+
return AccumBounds(self.min**other, self.max**other)
|
| 537 |
+
|
| 538 |
+
# non-integer exponent
|
| 539 |
+
# 0**neg or neg**frac yields complex
|
| 540 |
+
if (other.is_number or other.is_rational) and (
|
| 541 |
+
self.min.is_extended_nonnegative or (
|
| 542 |
+
other.is_extended_nonnegative and
|
| 543 |
+
self.min.is_extended_nonnegative)):
|
| 544 |
+
num, den = other.as_numer_denom()
|
| 545 |
+
if num is S.One:
|
| 546 |
+
return AccumBounds(*[i**(1/den) for i in self.args])
|
| 547 |
+
|
| 548 |
+
elif den is not S.One: # e.g. if other is not Float
|
| 549 |
+
return (self**num)**(1/den) # ok for non-negative base
|
| 550 |
+
|
| 551 |
+
if isinstance(other, AccumBounds):
|
| 552 |
+
if (self.min.is_extended_positive or
|
| 553 |
+
self.min.is_extended_nonnegative and
|
| 554 |
+
other.min.is_extended_nonnegative):
|
| 555 |
+
p = [self**i for i in other.args]
|
| 556 |
+
if not any(i.is_Pow for i in p):
|
| 557 |
+
a = [j for i in p for j in i.args or (i,)]
|
| 558 |
+
try:
|
| 559 |
+
return self.func(min(a), max(a))
|
| 560 |
+
except TypeError: # can't sort
|
| 561 |
+
pass
|
| 562 |
+
|
| 563 |
+
return Pow(self, other, evaluate=False)
|
| 564 |
+
|
| 565 |
+
return NotImplemented
|
| 566 |
+
|
| 567 |
+
@_sympifyit('other', NotImplemented)
|
| 568 |
+
def __rpow__(self, other):
|
| 569 |
+
if other.is_real and other.is_extended_nonnegative and (
|
| 570 |
+
self.max - self.min).is_extended_positive:
|
| 571 |
+
if other is S.One:
|
| 572 |
+
return S.One
|
| 573 |
+
if other.is_extended_positive:
|
| 574 |
+
a, b = [other**i for i in self.args]
|
| 575 |
+
if min(a, b) != a:
|
| 576 |
+
a, b = b, a
|
| 577 |
+
return self.func(a, b)
|
| 578 |
+
if other.is_zero:
|
| 579 |
+
if self.min.is_zero:
|
| 580 |
+
return self.func(0, 1)
|
| 581 |
+
if self.min.is_extended_positive:
|
| 582 |
+
return S.Zero
|
| 583 |
+
|
| 584 |
+
return Pow(other, self, evaluate=False)
|
| 585 |
+
|
| 586 |
+
def __abs__(self):
|
| 587 |
+
if self.max.is_extended_negative:
|
| 588 |
+
return self.__neg__()
|
| 589 |
+
elif self.min.is_extended_negative:
|
| 590 |
+
return AccumBounds(S.Zero, Max(abs(self.min), self.max))
|
| 591 |
+
else:
|
| 592 |
+
return self
|
| 593 |
+
|
| 594 |
+
|
| 595 |
+
def __contains__(self, other):
|
| 596 |
+
"""
|
| 597 |
+
Returns ``True`` if other is contained in self, where other
|
| 598 |
+
belongs to extended real numbers, ``False`` if not contained,
|
| 599 |
+
otherwise TypeError is raised.
|
| 600 |
+
|
| 601 |
+
Examples
|
| 602 |
+
========
|
| 603 |
+
|
| 604 |
+
>>> from sympy import AccumBounds, oo
|
| 605 |
+
>>> 1 in AccumBounds(-1, 3)
|
| 606 |
+
True
|
| 607 |
+
|
| 608 |
+
-oo and oo go together as limits (in AccumulationBounds).
|
| 609 |
+
|
| 610 |
+
>>> -oo in AccumBounds(1, oo)
|
| 611 |
+
True
|
| 612 |
+
|
| 613 |
+
>>> oo in AccumBounds(-oo, 0)
|
| 614 |
+
True
|
| 615 |
+
|
| 616 |
+
"""
|
| 617 |
+
other = _sympify(other)
|
| 618 |
+
|
| 619 |
+
if other in (S.Infinity, S.NegativeInfinity):
|
| 620 |
+
if self.min is S.NegativeInfinity or self.max is S.Infinity:
|
| 621 |
+
return True
|
| 622 |
+
return False
|
| 623 |
+
|
| 624 |
+
rv = And(self.min <= other, self.max >= other)
|
| 625 |
+
if rv not in (True, False):
|
| 626 |
+
raise TypeError("input failed to evaluate")
|
| 627 |
+
return rv
|
| 628 |
+
|
| 629 |
+
def intersection(self, other):
|
| 630 |
+
"""
|
| 631 |
+
Returns the intersection of 'self' and 'other'.
|
| 632 |
+
Here other can be an instance of :py:class:`~.FiniteSet` or AccumulationBounds.
|
| 633 |
+
|
| 634 |
+
Parameters
|
| 635 |
+
==========
|
| 636 |
+
|
| 637 |
+
other : AccumulationBounds
|
| 638 |
+
Another AccumulationBounds object with which the intersection
|
| 639 |
+
has to be computed.
|
| 640 |
+
|
| 641 |
+
Returns
|
| 642 |
+
=======
|
| 643 |
+
|
| 644 |
+
AccumulationBounds
|
| 645 |
+
Intersection of ``self`` and ``other``.
|
| 646 |
+
|
| 647 |
+
Examples
|
| 648 |
+
========
|
| 649 |
+
|
| 650 |
+
>>> from sympy import AccumBounds, FiniteSet
|
| 651 |
+
>>> AccumBounds(1, 3).intersection(AccumBounds(2, 4))
|
| 652 |
+
AccumBounds(2, 3)
|
| 653 |
+
|
| 654 |
+
>>> AccumBounds(1, 3).intersection(AccumBounds(4, 6))
|
| 655 |
+
EmptySet
|
| 656 |
+
|
| 657 |
+
>>> AccumBounds(1, 4).intersection(FiniteSet(1, 2, 5))
|
| 658 |
+
{1, 2}
|
| 659 |
+
|
| 660 |
+
"""
|
| 661 |
+
if not isinstance(other, (AccumBounds, FiniteSet)):
|
| 662 |
+
raise TypeError(
|
| 663 |
+
"Input must be AccumulationBounds or FiniteSet object")
|
| 664 |
+
|
| 665 |
+
if isinstance(other, FiniteSet):
|
| 666 |
+
fin_set = S.EmptySet
|
| 667 |
+
for i in other:
|
| 668 |
+
if i in self:
|
| 669 |
+
fin_set = fin_set + FiniteSet(i)
|
| 670 |
+
return fin_set
|
| 671 |
+
|
| 672 |
+
if self.max < other.min or self.min > other.max:
|
| 673 |
+
return S.EmptySet
|
| 674 |
+
|
| 675 |
+
if self.min <= other.min:
|
| 676 |
+
if self.max <= other.max:
|
| 677 |
+
return AccumBounds(other.min, self.max)
|
| 678 |
+
if self.max > other.max:
|
| 679 |
+
return other
|
| 680 |
+
|
| 681 |
+
if other.min <= self.min:
|
| 682 |
+
if other.max < self.max:
|
| 683 |
+
return AccumBounds(self.min, other.max)
|
| 684 |
+
if other.max > self.max:
|
| 685 |
+
return self
|
| 686 |
+
|
| 687 |
+
def union(self, other):
|
| 688 |
+
# TODO : Devise a better method for Union of AccumBounds
|
| 689 |
+
# this method is not actually correct and
|
| 690 |
+
# can be made better
|
| 691 |
+
if not isinstance(other, AccumBounds):
|
| 692 |
+
raise TypeError(
|
| 693 |
+
"Input must be AccumulationBounds or FiniteSet object")
|
| 694 |
+
|
| 695 |
+
if self.min <= other.min and self.max >= other.min:
|
| 696 |
+
return AccumBounds(self.min, Max(self.max, other.max))
|
| 697 |
+
|
| 698 |
+
if other.min <= self.min and other.max >= self.min:
|
| 699 |
+
return AccumBounds(other.min, Max(self.max, other.max))
|
| 700 |
+
|
| 701 |
+
|
| 702 |
+
@dispatch(AccumulationBounds, AccumulationBounds) # type: ignore # noqa:F811
|
| 703 |
+
def _eval_is_le(lhs, rhs): # noqa:F811
|
| 704 |
+
if is_le(lhs.max, rhs.min):
|
| 705 |
+
return True
|
| 706 |
+
if is_gt(lhs.min, rhs.max):
|
| 707 |
+
return False
|
| 708 |
+
|
| 709 |
+
|
| 710 |
+
@dispatch(AccumulationBounds, Basic) # type: ignore # noqa:F811
|
| 711 |
+
def _eval_is_le(lhs, rhs): # noqa: F811
|
| 712 |
+
|
| 713 |
+
"""
|
| 714 |
+
Returns ``True `` if range of values attained by ``lhs`` AccumulationBounds
|
| 715 |
+
object is greater than the range of values attained by ``rhs``,
|
| 716 |
+
where ``rhs`` may be any value of type AccumulationBounds object or
|
| 717 |
+
extended real number value, ``False`` if ``rhs`` satisfies
|
| 718 |
+
the same property, else an unevaluated :py:class:`~.Relational`.
|
| 719 |
+
|
| 720 |
+
Examples
|
| 721 |
+
========
|
| 722 |
+
|
| 723 |
+
>>> from sympy import AccumBounds, oo
|
| 724 |
+
>>> AccumBounds(1, 3) > AccumBounds(4, oo)
|
| 725 |
+
False
|
| 726 |
+
>>> AccumBounds(1, 4) > AccumBounds(3, 4)
|
| 727 |
+
AccumBounds(1, 4) > AccumBounds(3, 4)
|
| 728 |
+
>>> AccumBounds(1, oo) > -1
|
| 729 |
+
True
|
| 730 |
+
|
| 731 |
+
"""
|
| 732 |
+
if not rhs.is_extended_real:
|
| 733 |
+
raise TypeError(
|
| 734 |
+
"Invalid comparison of %s %s" %
|
| 735 |
+
(type(rhs), rhs))
|
| 736 |
+
elif rhs.is_comparable:
|
| 737 |
+
if is_le(lhs.max, rhs):
|
| 738 |
+
return True
|
| 739 |
+
if is_gt(lhs.min, rhs):
|
| 740 |
+
return False
|
| 741 |
+
|
| 742 |
+
|
| 743 |
+
@dispatch(AccumulationBounds, AccumulationBounds)
|
| 744 |
+
def _eval_is_ge(lhs, rhs): # noqa:F811
|
| 745 |
+
if is_ge(lhs.min, rhs.max):
|
| 746 |
+
return True
|
| 747 |
+
if is_lt(lhs.max, rhs.min):
|
| 748 |
+
return False
|
| 749 |
+
|
| 750 |
+
|
| 751 |
+
@dispatch(AccumulationBounds, Expr) # type:ignore
|
| 752 |
+
def _eval_is_ge(lhs, rhs): # noqa: F811
|
| 753 |
+
"""
|
| 754 |
+
Returns ``True`` if range of values attained by ``lhs`` AccumulationBounds
|
| 755 |
+
object is less that the range of values attained by ``rhs``, where
|
| 756 |
+
other may be any value of type AccumulationBounds object or extended
|
| 757 |
+
real number value, ``False`` if ``rhs`` satisfies the same
|
| 758 |
+
property, else an unevaluated :py:class:`~.Relational`.
|
| 759 |
+
|
| 760 |
+
Examples
|
| 761 |
+
========
|
| 762 |
+
|
| 763 |
+
>>> from sympy import AccumBounds, oo
|
| 764 |
+
>>> AccumBounds(1, 3) >= AccumBounds(4, oo)
|
| 765 |
+
False
|
| 766 |
+
>>> AccumBounds(1, 4) >= AccumBounds(3, 4)
|
| 767 |
+
AccumBounds(1, 4) >= AccumBounds(3, 4)
|
| 768 |
+
>>> AccumBounds(1, oo) >= 1
|
| 769 |
+
True
|
| 770 |
+
"""
|
| 771 |
+
|
| 772 |
+
if not rhs.is_extended_real:
|
| 773 |
+
raise TypeError(
|
| 774 |
+
"Invalid comparison of %s %s" %
|
| 775 |
+
(type(rhs), rhs))
|
| 776 |
+
elif rhs.is_comparable:
|
| 777 |
+
if is_ge(lhs.min, rhs):
|
| 778 |
+
return True
|
| 779 |
+
if is_lt(lhs.max, rhs):
|
| 780 |
+
return False
|
| 781 |
+
|
| 782 |
+
|
| 783 |
+
@dispatch(Expr, AccumulationBounds) # type:ignore
|
| 784 |
+
def _eval_is_ge(lhs, rhs): # noqa:F811
|
| 785 |
+
if not lhs.is_extended_real:
|
| 786 |
+
raise TypeError(
|
| 787 |
+
"Invalid comparison of %s %s" %
|
| 788 |
+
(type(lhs), lhs))
|
| 789 |
+
elif lhs.is_comparable:
|
| 790 |
+
if is_le(rhs.max, lhs):
|
| 791 |
+
return True
|
| 792 |
+
if is_gt(rhs.min, lhs):
|
| 793 |
+
return False
|
| 794 |
+
|
| 795 |
+
|
| 796 |
+
@dispatch(AccumulationBounds, AccumulationBounds) # type:ignore
|
| 797 |
+
def _eval_is_ge(lhs, rhs): # noqa:F811
|
| 798 |
+
if is_ge(lhs.min, rhs.max):
|
| 799 |
+
return True
|
| 800 |
+
if is_lt(lhs.max, rhs.min):
|
| 801 |
+
return False
|
| 802 |
+
|
| 803 |
+
# setting an alias for AccumulationBounds
|
| 804 |
+
AccumBounds = AccumulationBounds
|
infer_4_47_1/lib/python3.10/site-packages/sympy/calculus/finite_diff.py
ADDED
|
@@ -0,0 +1,476 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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+
Finite difference weights
|
| 3 |
+
=========================
|
| 4 |
+
|
| 5 |
+
This module implements an algorithm for efficient generation of finite
|
| 6 |
+
difference weights for ordinary differentials of functions for
|
| 7 |
+
derivatives from 0 (interpolation) up to arbitrary order.
|
| 8 |
+
|
| 9 |
+
The core algorithm is provided in the finite difference weight generating
|
| 10 |
+
function (``finite_diff_weights``), and two convenience functions are provided
|
| 11 |
+
for:
|
| 12 |
+
|
| 13 |
+
- estimating a derivative (or interpolate) directly from a series of points
|
| 14 |
+
is also provided (``apply_finite_diff``).
|
| 15 |
+
- differentiating by using finite difference approximations
|
| 16 |
+
(``differentiate_finite``).
|
| 17 |
+
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
from sympy.core.function import Derivative
|
| 21 |
+
from sympy.core.singleton import S
|
| 22 |
+
from sympy.core.function import Subs
|
| 23 |
+
from sympy.core.traversal import preorder_traversal
|
| 24 |
+
from sympy.utilities.exceptions import sympy_deprecation_warning
|
| 25 |
+
from sympy.utilities.iterables import iterable
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def finite_diff_weights(order, x_list, x0=S.One):
|
| 30 |
+
"""
|
| 31 |
+
Calculates the finite difference weights for an arbitrarily spaced
|
| 32 |
+
one-dimensional grid (``x_list``) for derivatives at ``x0`` of order
|
| 33 |
+
0, 1, ..., up to ``order`` using a recursive formula. Order of accuracy
|
| 34 |
+
is at least ``len(x_list) - order``, if ``x_list`` is defined correctly.
|
| 35 |
+
|
| 36 |
+
Parameters
|
| 37 |
+
==========
|
| 38 |
+
|
| 39 |
+
order: int
|
| 40 |
+
Up to what derivative order weights should be calculated.
|
| 41 |
+
0 corresponds to interpolation.
|
| 42 |
+
x_list: sequence
|
| 43 |
+
Sequence of (unique) values for the independent variable.
|
| 44 |
+
It is useful (but not necessary) to order ``x_list`` from
|
| 45 |
+
nearest to furthest from ``x0``; see examples below.
|
| 46 |
+
x0: Number or Symbol
|
| 47 |
+
Root or value of the independent variable for which the finite
|
| 48 |
+
difference weights should be generated. Default is ``S.One``.
|
| 49 |
+
|
| 50 |
+
Returns
|
| 51 |
+
=======
|
| 52 |
+
|
| 53 |
+
list
|
| 54 |
+
A list of sublists, each corresponding to coefficients for
|
| 55 |
+
increasing derivative order, and each containing lists of
|
| 56 |
+
coefficients for increasing subsets of x_list.
|
| 57 |
+
|
| 58 |
+
Examples
|
| 59 |
+
========
|
| 60 |
+
|
| 61 |
+
>>> from sympy import finite_diff_weights, S
|
| 62 |
+
>>> res = finite_diff_weights(1, [-S(1)/2, S(1)/2, S(3)/2, S(5)/2], 0)
|
| 63 |
+
>>> res
|
| 64 |
+
[[[1, 0, 0, 0],
|
| 65 |
+
[1/2, 1/2, 0, 0],
|
| 66 |
+
[3/8, 3/4, -1/8, 0],
|
| 67 |
+
[5/16, 15/16, -5/16, 1/16]],
|
| 68 |
+
[[0, 0, 0, 0],
|
| 69 |
+
[-1, 1, 0, 0],
|
| 70 |
+
[-1, 1, 0, 0],
|
| 71 |
+
[-23/24, 7/8, 1/8, -1/24]]]
|
| 72 |
+
>>> res[0][-1] # FD weights for 0th derivative, using full x_list
|
| 73 |
+
[5/16, 15/16, -5/16, 1/16]
|
| 74 |
+
>>> res[1][-1] # FD weights for 1st derivative
|
| 75 |
+
[-23/24, 7/8, 1/8, -1/24]
|
| 76 |
+
>>> res[1][-2] # FD weights for 1st derivative, using x_list[:-1]
|
| 77 |
+
[-1, 1, 0, 0]
|
| 78 |
+
>>> res[1][-1][0] # FD weight for 1st deriv. for x_list[0]
|
| 79 |
+
-23/24
|
| 80 |
+
>>> res[1][-1][1] # FD weight for 1st deriv. for x_list[1], etc.
|
| 81 |
+
7/8
|
| 82 |
+
|
| 83 |
+
Each sublist contains the most accurate formula at the end.
|
| 84 |
+
Note, that in the above example ``res[1][1]`` is the same as ``res[1][2]``.
|
| 85 |
+
Since res[1][2] has an order of accuracy of
|
| 86 |
+
``len(x_list[:3]) - order = 3 - 1 = 2``, the same is true for ``res[1][1]``!
|
| 87 |
+
|
| 88 |
+
>>> res = finite_diff_weights(1, [S(0), S(1), -S(1), S(2), -S(2)], 0)[1]
|
| 89 |
+
>>> res
|
| 90 |
+
[[0, 0, 0, 0, 0],
|
| 91 |
+
[-1, 1, 0, 0, 0],
|
| 92 |
+
[0, 1/2, -1/2, 0, 0],
|
| 93 |
+
[-1/2, 1, -1/3, -1/6, 0],
|
| 94 |
+
[0, 2/3, -2/3, -1/12, 1/12]]
|
| 95 |
+
>>> res[0] # no approximation possible, using x_list[0] only
|
| 96 |
+
[0, 0, 0, 0, 0]
|
| 97 |
+
>>> res[1] # classic forward step approximation
|
| 98 |
+
[-1, 1, 0, 0, 0]
|
| 99 |
+
>>> res[2] # classic centered approximation
|
| 100 |
+
[0, 1/2, -1/2, 0, 0]
|
| 101 |
+
>>> res[3:] # higher order approximations
|
| 102 |
+
[[-1/2, 1, -1/3, -1/6, 0], [0, 2/3, -2/3, -1/12, 1/12]]
|
| 103 |
+
|
| 104 |
+
Let us compare this to a differently defined ``x_list``. Pay attention to
|
| 105 |
+
``foo[i][k]`` corresponding to the gridpoint defined by ``x_list[k]``.
|
| 106 |
+
|
| 107 |
+
>>> foo = finite_diff_weights(1, [-S(2), -S(1), S(0), S(1), S(2)], 0)[1]
|
| 108 |
+
>>> foo
|
| 109 |
+
[[0, 0, 0, 0, 0],
|
| 110 |
+
[-1, 1, 0, 0, 0],
|
| 111 |
+
[1/2, -2, 3/2, 0, 0],
|
| 112 |
+
[1/6, -1, 1/2, 1/3, 0],
|
| 113 |
+
[1/12, -2/3, 0, 2/3, -1/12]]
|
| 114 |
+
>>> foo[1] # not the same and of lower accuracy as res[1]!
|
| 115 |
+
[-1, 1, 0, 0, 0]
|
| 116 |
+
>>> foo[2] # classic double backward step approximation
|
| 117 |
+
[1/2, -2, 3/2, 0, 0]
|
| 118 |
+
>>> foo[4] # the same as res[4]
|
| 119 |
+
[1/12, -2/3, 0, 2/3, -1/12]
|
| 120 |
+
|
| 121 |
+
Note that, unless you plan on using approximations based on subsets of
|
| 122 |
+
``x_list``, the order of gridpoints does not matter.
|
| 123 |
+
|
| 124 |
+
The capability to generate weights at arbitrary points can be
|
| 125 |
+
used e.g. to minimize Runge's phenomenon by using Chebyshev nodes:
|
| 126 |
+
|
| 127 |
+
>>> from sympy import cos, symbols, pi, simplify
|
| 128 |
+
>>> N, (h, x) = 4, symbols('h x')
|
| 129 |
+
>>> x_list = [x+h*cos(i*pi/(N)) for i in range(N,-1,-1)] # chebyshev nodes
|
| 130 |
+
>>> print(x_list)
|
| 131 |
+
[-h + x, -sqrt(2)*h/2 + x, x, sqrt(2)*h/2 + x, h + x]
|
| 132 |
+
>>> mycoeffs = finite_diff_weights(1, x_list, 0)[1][4]
|
| 133 |
+
>>> [simplify(c) for c in mycoeffs] #doctest: +NORMALIZE_WHITESPACE
|
| 134 |
+
[(h**3/2 + h**2*x - 3*h*x**2 - 4*x**3)/h**4,
|
| 135 |
+
(-sqrt(2)*h**3 - 4*h**2*x + 3*sqrt(2)*h*x**2 + 8*x**3)/h**4,
|
| 136 |
+
(6*h**2*x - 8*x**3)/h**4,
|
| 137 |
+
(sqrt(2)*h**3 - 4*h**2*x - 3*sqrt(2)*h*x**2 + 8*x**3)/h**4,
|
| 138 |
+
(-h**3/2 + h**2*x + 3*h*x**2 - 4*x**3)/h**4]
|
| 139 |
+
|
| 140 |
+
Notes
|
| 141 |
+
=====
|
| 142 |
+
|
| 143 |
+
If weights for a finite difference approximation of 3rd order
|
| 144 |
+
derivative is wanted, weights for 0th, 1st and 2nd order are
|
| 145 |
+
calculated "for free", so are formulae using subsets of ``x_list``.
|
| 146 |
+
This is something one can take advantage of to save computational cost.
|
| 147 |
+
Be aware that one should define ``x_list`` from nearest to furthest from
|
| 148 |
+
``x0``. If not, subsets of ``x_list`` will yield poorer approximations,
|
| 149 |
+
which might not grand an order of accuracy of ``len(x_list) - order``.
|
| 150 |
+
|
| 151 |
+
See also
|
| 152 |
+
========
|
| 153 |
+
|
| 154 |
+
sympy.calculus.finite_diff.apply_finite_diff
|
| 155 |
+
|
| 156 |
+
References
|
| 157 |
+
==========
|
| 158 |
+
|
| 159 |
+
.. [1] Generation of Finite Difference Formulas on Arbitrarily Spaced
|
| 160 |
+
Grids, Bengt Fornberg; Mathematics of computation; 51; 184;
|
| 161 |
+
(1988); 699-706; doi:10.1090/S0025-5718-1988-0935077-0
|
| 162 |
+
|
| 163 |
+
"""
|
| 164 |
+
# The notation below closely corresponds to the one used in the paper.
|
| 165 |
+
order = S(order)
|
| 166 |
+
if not order.is_number:
|
| 167 |
+
raise ValueError("Cannot handle symbolic order.")
|
| 168 |
+
if order < 0:
|
| 169 |
+
raise ValueError("Negative derivative order illegal.")
|
| 170 |
+
if int(order) != order:
|
| 171 |
+
raise ValueError("Non-integer order illegal")
|
| 172 |
+
M = order
|
| 173 |
+
N = len(x_list) - 1
|
| 174 |
+
delta = [[[0 for nu in range(N+1)] for n in range(N+1)] for
|
| 175 |
+
m in range(M+1)]
|
| 176 |
+
delta[0][0][0] = S.One
|
| 177 |
+
c1 = S.One
|
| 178 |
+
for n in range(1, N+1):
|
| 179 |
+
c2 = S.One
|
| 180 |
+
for nu in range(n):
|
| 181 |
+
c3 = x_list[n] - x_list[nu]
|
| 182 |
+
c2 = c2 * c3
|
| 183 |
+
if n <= M:
|
| 184 |
+
delta[n][n-1][nu] = 0
|
| 185 |
+
for m in range(min(n, M)+1):
|
| 186 |
+
delta[m][n][nu] = (x_list[n]-x0)*delta[m][n-1][nu] -\
|
| 187 |
+
m*delta[m-1][n-1][nu]
|
| 188 |
+
delta[m][n][nu] /= c3
|
| 189 |
+
for m in range(min(n, M)+1):
|
| 190 |
+
delta[m][n][n] = c1/c2*(m*delta[m-1][n-1][n-1] -
|
| 191 |
+
(x_list[n-1]-x0)*delta[m][n-1][n-1])
|
| 192 |
+
c1 = c2
|
| 193 |
+
return delta
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def apply_finite_diff(order, x_list, y_list, x0=S.Zero):
|
| 197 |
+
"""
|
| 198 |
+
Calculates the finite difference approximation of
|
| 199 |
+
the derivative of requested order at ``x0`` from points
|
| 200 |
+
provided in ``x_list`` and ``y_list``.
|
| 201 |
+
|
| 202 |
+
Parameters
|
| 203 |
+
==========
|
| 204 |
+
|
| 205 |
+
order: int
|
| 206 |
+
order of derivative to approximate. 0 corresponds to interpolation.
|
| 207 |
+
x_list: sequence
|
| 208 |
+
Sequence of (unique) values for the independent variable.
|
| 209 |
+
y_list: sequence
|
| 210 |
+
The function value at corresponding values for the independent
|
| 211 |
+
variable in x_list.
|
| 212 |
+
x0: Number or Symbol
|
| 213 |
+
At what value of the independent variable the derivative should be
|
| 214 |
+
evaluated. Defaults to 0.
|
| 215 |
+
|
| 216 |
+
Returns
|
| 217 |
+
=======
|
| 218 |
+
|
| 219 |
+
sympy.core.add.Add or sympy.core.numbers.Number
|
| 220 |
+
The finite difference expression approximating the requested
|
| 221 |
+
derivative order at ``x0``.
|
| 222 |
+
|
| 223 |
+
Examples
|
| 224 |
+
========
|
| 225 |
+
|
| 226 |
+
>>> from sympy import apply_finite_diff
|
| 227 |
+
>>> cube = lambda arg: (1.0*arg)**3
|
| 228 |
+
>>> xlist = range(-3,3+1)
|
| 229 |
+
>>> apply_finite_diff(2, xlist, map(cube, xlist), 2) - 12 # doctest: +SKIP
|
| 230 |
+
-3.55271367880050e-15
|
| 231 |
+
|
| 232 |
+
we see that the example above only contain rounding errors.
|
| 233 |
+
apply_finite_diff can also be used on more abstract objects:
|
| 234 |
+
|
| 235 |
+
>>> from sympy import IndexedBase, Idx
|
| 236 |
+
>>> x, y = map(IndexedBase, 'xy')
|
| 237 |
+
>>> i = Idx('i')
|
| 238 |
+
>>> x_list, y_list = zip(*[(x[i+j], y[i+j]) for j in range(-1,2)])
|
| 239 |
+
>>> apply_finite_diff(1, x_list, y_list, x[i])
|
| 240 |
+
((x[i + 1] - x[i])/(-x[i - 1] + x[i]) - 1)*y[i]/(x[i + 1] - x[i]) -
|
| 241 |
+
(x[i + 1] - x[i])*y[i - 1]/((x[i + 1] - x[i - 1])*(-x[i - 1] + x[i])) +
|
| 242 |
+
(-x[i - 1] + x[i])*y[i + 1]/((x[i + 1] - x[i - 1])*(x[i + 1] - x[i]))
|
| 243 |
+
|
| 244 |
+
Notes
|
| 245 |
+
=====
|
| 246 |
+
|
| 247 |
+
Order = 0 corresponds to interpolation.
|
| 248 |
+
Only supply so many points you think makes sense
|
| 249 |
+
to around x0 when extracting the derivative (the function
|
| 250 |
+
need to be well behaved within that region). Also beware
|
| 251 |
+
of Runge's phenomenon.
|
| 252 |
+
|
| 253 |
+
See also
|
| 254 |
+
========
|
| 255 |
+
|
| 256 |
+
sympy.calculus.finite_diff.finite_diff_weights
|
| 257 |
+
|
| 258 |
+
References
|
| 259 |
+
==========
|
| 260 |
+
|
| 261 |
+
Fortran 90 implementation with Python interface for numerics: finitediff_
|
| 262 |
+
|
| 263 |
+
.. _finitediff: https://github.com/bjodah/finitediff
|
| 264 |
+
|
| 265 |
+
"""
|
| 266 |
+
|
| 267 |
+
# In the original paper the following holds for the notation:
|
| 268 |
+
# M = order
|
| 269 |
+
# N = len(x_list) - 1
|
| 270 |
+
|
| 271 |
+
N = len(x_list) - 1
|
| 272 |
+
if len(x_list) != len(y_list):
|
| 273 |
+
raise ValueError("x_list and y_list not equal in length.")
|
| 274 |
+
|
| 275 |
+
delta = finite_diff_weights(order, x_list, x0)
|
| 276 |
+
|
| 277 |
+
derivative = 0
|
| 278 |
+
for nu in range(len(x_list)):
|
| 279 |
+
derivative += delta[order][N][nu]*y_list[nu]
|
| 280 |
+
return derivative
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
def _as_finite_diff(derivative, points=1, x0=None, wrt=None):
|
| 284 |
+
"""
|
| 285 |
+
Returns an approximation of a derivative of a function in
|
| 286 |
+
the form of a finite difference formula. The expression is a
|
| 287 |
+
weighted sum of the function at a number of discrete values of
|
| 288 |
+
(one of) the independent variable(s).
|
| 289 |
+
|
| 290 |
+
Parameters
|
| 291 |
+
==========
|
| 292 |
+
|
| 293 |
+
derivative: a Derivative instance
|
| 294 |
+
|
| 295 |
+
points: sequence or coefficient, optional
|
| 296 |
+
If sequence: discrete values (length >= order+1) of the
|
| 297 |
+
independent variable used for generating the finite
|
| 298 |
+
difference weights.
|
| 299 |
+
If it is a coefficient, it will be used as the step-size
|
| 300 |
+
for generating an equidistant sequence of length order+1
|
| 301 |
+
centered around ``x0``. default: 1 (step-size 1)
|
| 302 |
+
|
| 303 |
+
x0: number or Symbol, optional
|
| 304 |
+
the value of the independent variable (``wrt``) at which the
|
| 305 |
+
derivative is to be approximated. Default: same as ``wrt``.
|
| 306 |
+
|
| 307 |
+
wrt: Symbol, optional
|
| 308 |
+
"with respect to" the variable for which the (partial)
|
| 309 |
+
derivative is to be approximated for. If not provided it
|
| 310 |
+
is required that the Derivative is ordinary. Default: ``None``.
|
| 311 |
+
|
| 312 |
+
Examples
|
| 313 |
+
========
|
| 314 |
+
|
| 315 |
+
>>> from sympy import symbols, Function, exp, sqrt, Symbol
|
| 316 |
+
>>> from sympy.calculus.finite_diff import _as_finite_diff
|
| 317 |
+
>>> x, h = symbols('x h')
|
| 318 |
+
>>> f = Function('f')
|
| 319 |
+
>>> _as_finite_diff(f(x).diff(x))
|
| 320 |
+
-f(x - 1/2) + f(x + 1/2)
|
| 321 |
+
|
| 322 |
+
The default step size and number of points are 1 and ``order + 1``
|
| 323 |
+
respectively. We can change the step size by passing a symbol
|
| 324 |
+
as a parameter:
|
| 325 |
+
|
| 326 |
+
>>> _as_finite_diff(f(x).diff(x), h)
|
| 327 |
+
-f(-h/2 + x)/h + f(h/2 + x)/h
|
| 328 |
+
|
| 329 |
+
We can also specify the discretized values to be used in a sequence:
|
| 330 |
+
|
| 331 |
+
>>> _as_finite_diff(f(x).diff(x), [x, x+h, x+2*h])
|
| 332 |
+
-3*f(x)/(2*h) + 2*f(h + x)/h - f(2*h + x)/(2*h)
|
| 333 |
+
|
| 334 |
+
The algorithm is not restricted to use equidistant spacing, nor
|
| 335 |
+
do we need to make the approximation around ``x0``, but we can get
|
| 336 |
+
an expression estimating the derivative at an offset:
|
| 337 |
+
|
| 338 |
+
>>> e, sq2 = exp(1), sqrt(2)
|
| 339 |
+
>>> xl = [x-h, x+h, x+e*h]
|
| 340 |
+
>>> _as_finite_diff(f(x).diff(x, 1), xl, x+h*sq2)
|
| 341 |
+
2*h*((h + sqrt(2)*h)/(2*h) - (-sqrt(2)*h + h)/(2*h))*f(E*h + x)/((-h + E*h)*(h + E*h)) +
|
| 342 |
+
(-(-sqrt(2)*h + h)/(2*h) - (-sqrt(2)*h + E*h)/(2*h))*f(-h + x)/(h + E*h) +
|
| 343 |
+
(-(h + sqrt(2)*h)/(2*h) + (-sqrt(2)*h + E*h)/(2*h))*f(h + x)/(-h + E*h)
|
| 344 |
+
|
| 345 |
+
Partial derivatives are also supported:
|
| 346 |
+
|
| 347 |
+
>>> y = Symbol('y')
|
| 348 |
+
>>> d2fdxdy=f(x,y).diff(x,y)
|
| 349 |
+
>>> _as_finite_diff(d2fdxdy, wrt=x)
|
| 350 |
+
-Derivative(f(x - 1/2, y), y) + Derivative(f(x + 1/2, y), y)
|
| 351 |
+
|
| 352 |
+
See also
|
| 353 |
+
========
|
| 354 |
+
|
| 355 |
+
sympy.calculus.finite_diff.apply_finite_diff
|
| 356 |
+
sympy.calculus.finite_diff.finite_diff_weights
|
| 357 |
+
|
| 358 |
+
"""
|
| 359 |
+
if derivative.is_Derivative:
|
| 360 |
+
pass
|
| 361 |
+
elif derivative.is_Atom:
|
| 362 |
+
return derivative
|
| 363 |
+
else:
|
| 364 |
+
return derivative.fromiter(
|
| 365 |
+
[_as_finite_diff(ar, points, x0, wrt) for ar
|
| 366 |
+
in derivative.args], **derivative.assumptions0)
|
| 367 |
+
|
| 368 |
+
if wrt is None:
|
| 369 |
+
old = None
|
| 370 |
+
for v in derivative.variables:
|
| 371 |
+
if old is v:
|
| 372 |
+
continue
|
| 373 |
+
derivative = _as_finite_diff(derivative, points, x0, v)
|
| 374 |
+
old = v
|
| 375 |
+
return derivative
|
| 376 |
+
|
| 377 |
+
order = derivative.variables.count(wrt)
|
| 378 |
+
|
| 379 |
+
if x0 is None:
|
| 380 |
+
x0 = wrt
|
| 381 |
+
|
| 382 |
+
if not iterable(points):
|
| 383 |
+
if getattr(points, 'is_Function', False) and wrt in points.args:
|
| 384 |
+
points = points.subs(wrt, x0)
|
| 385 |
+
# points is simply the step-size, let's make it a
|
| 386 |
+
# equidistant sequence centered around x0
|
| 387 |
+
if order % 2 == 0:
|
| 388 |
+
# even order => odd number of points, grid point included
|
| 389 |
+
points = [x0 + points*i for i
|
| 390 |
+
in range(-order//2, order//2 + 1)]
|
| 391 |
+
else:
|
| 392 |
+
# odd order => even number of points, half-way wrt grid point
|
| 393 |
+
points = [x0 + points*S(i)/2 for i
|
| 394 |
+
in range(-order, order + 1, 2)]
|
| 395 |
+
others = [wrt, 0]
|
| 396 |
+
for v in set(derivative.variables):
|
| 397 |
+
if v == wrt:
|
| 398 |
+
continue
|
| 399 |
+
others += [v, derivative.variables.count(v)]
|
| 400 |
+
if len(points) < order+1:
|
| 401 |
+
raise ValueError("Too few points for order %d" % order)
|
| 402 |
+
return apply_finite_diff(order, points, [
|
| 403 |
+
Derivative(derivative.expr.subs({wrt: x}), *others) for
|
| 404 |
+
x in points], x0)
|
| 405 |
+
|
| 406 |
+
|
| 407 |
+
def differentiate_finite(expr, *symbols,
|
| 408 |
+
points=1, x0=None, wrt=None, evaluate=False):
|
| 409 |
+
r""" Differentiate expr and replace Derivatives with finite differences.
|
| 410 |
+
|
| 411 |
+
Parameters
|
| 412 |
+
==========
|
| 413 |
+
|
| 414 |
+
expr : expression
|
| 415 |
+
\*symbols : differentiate with respect to symbols
|
| 416 |
+
points: sequence, coefficient or undefined function, optional
|
| 417 |
+
see ``Derivative.as_finite_difference``
|
| 418 |
+
x0: number or Symbol, optional
|
| 419 |
+
see ``Derivative.as_finite_difference``
|
| 420 |
+
wrt: Symbol, optional
|
| 421 |
+
see ``Derivative.as_finite_difference``
|
| 422 |
+
|
| 423 |
+
Examples
|
| 424 |
+
========
|
| 425 |
+
|
| 426 |
+
>>> from sympy import sin, Function, differentiate_finite
|
| 427 |
+
>>> from sympy.abc import x, y, h
|
| 428 |
+
>>> f, g = Function('f'), Function('g')
|
| 429 |
+
>>> differentiate_finite(f(x)*g(x), x, points=[x-h, x+h])
|
| 430 |
+
-f(-h + x)*g(-h + x)/(2*h) + f(h + x)*g(h + x)/(2*h)
|
| 431 |
+
|
| 432 |
+
``differentiate_finite`` works on any expression, including the expressions
|
| 433 |
+
with embedded derivatives:
|
| 434 |
+
|
| 435 |
+
>>> differentiate_finite(f(x) + sin(x), x, 2)
|
| 436 |
+
-2*f(x) + f(x - 1) + f(x + 1) - 2*sin(x) + sin(x - 1) + sin(x + 1)
|
| 437 |
+
>>> differentiate_finite(f(x, y), x, y)
|
| 438 |
+
f(x - 1/2, y - 1/2) - f(x - 1/2, y + 1/2) - f(x + 1/2, y - 1/2) + f(x + 1/2, y + 1/2)
|
| 439 |
+
>>> differentiate_finite(f(x)*g(x).diff(x), x)
|
| 440 |
+
(-g(x) + g(x + 1))*f(x + 1/2) - (g(x) - g(x - 1))*f(x - 1/2)
|
| 441 |
+
|
| 442 |
+
To make finite difference with non-constant discretization step use
|
| 443 |
+
undefined functions:
|
| 444 |
+
|
| 445 |
+
>>> dx = Function('dx')
|
| 446 |
+
>>> differentiate_finite(f(x)*g(x).diff(x), points=dx(x))
|
| 447 |
+
-(-g(x - dx(x)/2 - dx(x - dx(x)/2)/2)/dx(x - dx(x)/2) +
|
| 448 |
+
g(x - dx(x)/2 + dx(x - dx(x)/2)/2)/dx(x - dx(x)/2))*f(x - dx(x)/2)/dx(x) +
|
| 449 |
+
(-g(x + dx(x)/2 - dx(x + dx(x)/2)/2)/dx(x + dx(x)/2) +
|
| 450 |
+
g(x + dx(x)/2 + dx(x + dx(x)/2)/2)/dx(x + dx(x)/2))*f(x + dx(x)/2)/dx(x)
|
| 451 |
+
|
| 452 |
+
"""
|
| 453 |
+
if any(term.is_Derivative for term in list(preorder_traversal(expr))):
|
| 454 |
+
evaluate = False
|
| 455 |
+
|
| 456 |
+
Dexpr = expr.diff(*symbols, evaluate=evaluate)
|
| 457 |
+
if evaluate:
|
| 458 |
+
sympy_deprecation_warning("""
|
| 459 |
+
The evaluate flag to differentiate_finite() is deprecated.
|
| 460 |
+
|
| 461 |
+
evaluate=True expands the intermediate derivatives before computing
|
| 462 |
+
differences, but this usually not what you want, as it does not
|
| 463 |
+
satisfy the product rule.
|
| 464 |
+
""",
|
| 465 |
+
deprecated_since_version="1.5",
|
| 466 |
+
active_deprecations_target="deprecated-differentiate_finite-evaluate",
|
| 467 |
+
)
|
| 468 |
+
return Dexpr.replace(
|
| 469 |
+
lambda arg: arg.is_Derivative,
|
| 470 |
+
lambda arg: arg.as_finite_difference(points=points, x0=x0, wrt=wrt))
|
| 471 |
+
else:
|
| 472 |
+
DFexpr = Dexpr.as_finite_difference(points=points, x0=x0, wrt=wrt)
|
| 473 |
+
return DFexpr.replace(
|
| 474 |
+
lambda arg: isinstance(arg, Subs),
|
| 475 |
+
lambda arg: arg.expr.as_finite_difference(
|
| 476 |
+
points=points, x0=arg.point[0], wrt=arg.variables[0]))
|
infer_4_47_1/lib/python3.10/site-packages/sympy/calculus/tests/__init__.py
ADDED
|
File without changes
|
infer_4_47_1/lib/python3.10/site-packages/sympy/calculus/tests/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (178 Bytes). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/sympy/calculus/tests/__pycache__/test_accumulationbounds.cpython-310.pyc
ADDED
|
Binary file (12.6 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/sympy/calculus/tests/__pycache__/test_euler.cpython-310.pyc
ADDED
|
Binary file (3.82 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/sympy/calculus/tests/__pycache__/test_finite_diff.cpython-310.pyc
ADDED
|
Binary file (7.46 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/sympy/calculus/tests/__pycache__/test_singularities.cpython-310.pyc
ADDED
|
Binary file (5.6 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/sympy/calculus/tests/__pycache__/test_util.cpython-310.pyc
ADDED
|
Binary file (18.6 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/sympy/calculus/tests/test_accumulationbounds.py
ADDED
|
@@ -0,0 +1,336 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.core.numbers import (E, Rational, oo, pi, zoo)
|
| 2 |
+
from sympy.core.singleton import S
|
| 3 |
+
from sympy.core.symbol import Symbol
|
| 4 |
+
from sympy.functions.elementary.exponential import (exp, log)
|
| 5 |
+
from sympy.functions.elementary.miscellaneous import (Max, Min, sqrt)
|
| 6 |
+
from sympy.functions.elementary.trigonometric import (cos, sin, tan)
|
| 7 |
+
from sympy.calculus.accumulationbounds import AccumBounds
|
| 8 |
+
from sympy.core import Add, Mul, Pow
|
| 9 |
+
from sympy.core.expr import unchanged
|
| 10 |
+
from sympy.testing.pytest import raises, XFAIL
|
| 11 |
+
from sympy.abc import x
|
| 12 |
+
|
| 13 |
+
a = Symbol('a', real=True)
|
| 14 |
+
B = AccumBounds
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def test_AccumBounds():
|
| 18 |
+
assert B(1, 2).args == (1, 2)
|
| 19 |
+
assert B(1, 2).delta is S.One
|
| 20 |
+
assert B(1, 2).mid == Rational(3, 2)
|
| 21 |
+
assert B(1, 3).is_real == True
|
| 22 |
+
|
| 23 |
+
assert B(1, 1) is S.One
|
| 24 |
+
|
| 25 |
+
assert B(1, 2) + 1 == B(2, 3)
|
| 26 |
+
assert 1 + B(1, 2) == B(2, 3)
|
| 27 |
+
assert B(1, 2) + B(2, 3) == B(3, 5)
|
| 28 |
+
|
| 29 |
+
assert -B(1, 2) == B(-2, -1)
|
| 30 |
+
|
| 31 |
+
assert B(1, 2) - 1 == B(0, 1)
|
| 32 |
+
assert 1 - B(1, 2) == B(-1, 0)
|
| 33 |
+
assert B(2, 3) - B(1, 2) == B(0, 2)
|
| 34 |
+
|
| 35 |
+
assert x + B(1, 2) == Add(B(1, 2), x)
|
| 36 |
+
assert a + B(1, 2) == B(1 + a, 2 + a)
|
| 37 |
+
assert B(1, 2) - x == Add(B(1, 2), -x)
|
| 38 |
+
|
| 39 |
+
assert B(-oo, 1) + oo == B(-oo, oo)
|
| 40 |
+
assert B(1, oo) + oo is oo
|
| 41 |
+
assert B(1, oo) - oo == B(-oo, oo)
|
| 42 |
+
assert (-oo - B(-1, oo)) is -oo
|
| 43 |
+
assert B(-oo, 1) - oo is -oo
|
| 44 |
+
|
| 45 |
+
assert B(1, oo) - oo == B(-oo, oo)
|
| 46 |
+
assert B(-oo, 1) - (-oo) == B(-oo, oo)
|
| 47 |
+
assert (oo - B(1, oo)) == B(-oo, oo)
|
| 48 |
+
assert (-oo - B(1, oo)) is -oo
|
| 49 |
+
|
| 50 |
+
assert B(1, 2)/2 == B(S.Half, 1)
|
| 51 |
+
assert 2/B(2, 3) == B(Rational(2, 3), 1)
|
| 52 |
+
assert 1/B(-1, 1) == B(-oo, oo)
|
| 53 |
+
|
| 54 |
+
assert abs(B(1, 2)) == B(1, 2)
|
| 55 |
+
assert abs(B(-2, -1)) == B(1, 2)
|
| 56 |
+
assert abs(B(-2, 1)) == B(0, 2)
|
| 57 |
+
assert abs(B(-1, 2)) == B(0, 2)
|
| 58 |
+
c = Symbol('c')
|
| 59 |
+
raises(ValueError, lambda: B(0, c))
|
| 60 |
+
raises(ValueError, lambda: B(1, -1))
|
| 61 |
+
r = Symbol('r', real=True)
|
| 62 |
+
raises(ValueError, lambda: B(r, r - 1))
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def test_AccumBounds_mul():
|
| 66 |
+
assert B(1, 2)*2 == B(2, 4)
|
| 67 |
+
assert 2*B(1, 2) == B(2, 4)
|
| 68 |
+
assert B(1, 2)*B(2, 3) == B(2, 6)
|
| 69 |
+
assert B(0, 2)*B(2, oo) == B(0, oo)
|
| 70 |
+
l, r = B(-oo, oo), B(-a, a)
|
| 71 |
+
assert l*r == B(-oo, oo)
|
| 72 |
+
assert r*l == B(-oo, oo)
|
| 73 |
+
l, r = B(1, oo), B(-3, -2)
|
| 74 |
+
assert l*r == B(-oo, -2)
|
| 75 |
+
assert r*l == B(-oo, -2)
|
| 76 |
+
assert B(1, 2)*0 == 0
|
| 77 |
+
assert B(1, oo)*0 == B(0, oo)
|
| 78 |
+
assert B(-oo, 1)*0 == B(-oo, 0)
|
| 79 |
+
assert B(-oo, oo)*0 == B(-oo, oo)
|
| 80 |
+
|
| 81 |
+
assert B(1, 2)*x == Mul(B(1, 2), x, evaluate=False)
|
| 82 |
+
|
| 83 |
+
assert B(0, 2)*oo == B(0, oo)
|
| 84 |
+
assert B(-2, 0)*oo == B(-oo, 0)
|
| 85 |
+
assert B(0, 2)*(-oo) == B(-oo, 0)
|
| 86 |
+
assert B(-2, 0)*(-oo) == B(0, oo)
|
| 87 |
+
assert B(-1, 1)*oo == B(-oo, oo)
|
| 88 |
+
assert B(-1, 1)*(-oo) == B(-oo, oo)
|
| 89 |
+
assert B(-oo, oo)*oo == B(-oo, oo)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def test_AccumBounds_div():
|
| 93 |
+
assert B(-1, 3)/B(3, 4) == B(Rational(-1, 3), 1)
|
| 94 |
+
assert B(-2, 4)/B(-3, 4) == B(-oo, oo)
|
| 95 |
+
assert B(-3, -2)/B(-4, 0) == B(S.Half, oo)
|
| 96 |
+
|
| 97 |
+
# these two tests can have a better answer
|
| 98 |
+
# after Union of B is improved
|
| 99 |
+
assert B(-3, -2)/B(-2, 1) == B(-oo, oo)
|
| 100 |
+
assert B(2, 3)/B(-2, 2) == B(-oo, oo)
|
| 101 |
+
|
| 102 |
+
assert B(-3, -2)/B(0, 4) == B(-oo, Rational(-1, 2))
|
| 103 |
+
assert B(2, 4)/B(-3, 0) == B(-oo, Rational(-2, 3))
|
| 104 |
+
assert B(2, 4)/B(0, 3) == B(Rational(2, 3), oo)
|
| 105 |
+
|
| 106 |
+
assert B(0, 1)/B(0, 1) == B(0, oo)
|
| 107 |
+
assert B(-1, 0)/B(0, 1) == B(-oo, 0)
|
| 108 |
+
assert B(-1, 2)/B(-2, 2) == B(-oo, oo)
|
| 109 |
+
|
| 110 |
+
assert 1/B(-1, 2) == B(-oo, oo)
|
| 111 |
+
assert 1/B(0, 2) == B(S.Half, oo)
|
| 112 |
+
assert (-1)/B(0, 2) == B(-oo, Rational(-1, 2))
|
| 113 |
+
assert 1/B(-oo, 0) == B(-oo, 0)
|
| 114 |
+
assert 1/B(-1, 0) == B(-oo, -1)
|
| 115 |
+
assert (-2)/B(-oo, 0) == B(0, oo)
|
| 116 |
+
assert 1/B(-oo, -1) == B(-1, 0)
|
| 117 |
+
|
| 118 |
+
assert B(1, 2)/a == Mul(B(1, 2), 1/a, evaluate=False)
|
| 119 |
+
|
| 120 |
+
assert B(1, 2)/0 == B(1, 2)*zoo
|
| 121 |
+
assert B(1, oo)/oo == B(0, oo)
|
| 122 |
+
assert B(1, oo)/(-oo) == B(-oo, 0)
|
| 123 |
+
assert B(-oo, -1)/oo == B(-oo, 0)
|
| 124 |
+
assert B(-oo, -1)/(-oo) == B(0, oo)
|
| 125 |
+
assert B(-oo, oo)/oo == B(-oo, oo)
|
| 126 |
+
assert B(-oo, oo)/(-oo) == B(-oo, oo)
|
| 127 |
+
assert B(-1, oo)/oo == B(0, oo)
|
| 128 |
+
assert B(-1, oo)/(-oo) == B(-oo, 0)
|
| 129 |
+
assert B(-oo, 1)/oo == B(-oo, 0)
|
| 130 |
+
assert B(-oo, 1)/(-oo) == B(0, oo)
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def test_issue_18795():
|
| 134 |
+
r = Symbol('r', real=True)
|
| 135 |
+
a = B(-1,1)
|
| 136 |
+
c = B(7, oo)
|
| 137 |
+
b = B(-oo, oo)
|
| 138 |
+
assert c - tan(r) == B(7-tan(r), oo)
|
| 139 |
+
assert b + tan(r) == B(-oo, oo)
|
| 140 |
+
assert (a + r)/a == B(-oo, oo)*B(r - 1, r + 1)
|
| 141 |
+
assert (b + a)/a == B(-oo, oo)
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def test_AccumBounds_func():
|
| 145 |
+
assert (x**2 + 2*x + 1).subs(x, B(-1, 1)) == B(-1, 4)
|
| 146 |
+
assert exp(B(0, 1)) == B(1, E)
|
| 147 |
+
assert exp(B(-oo, oo)) == B(0, oo)
|
| 148 |
+
assert log(B(3, 6)) == B(log(3), log(6))
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
@XFAIL
|
| 152 |
+
def test_AccumBounds_powf():
|
| 153 |
+
nn = Symbol('nn', nonnegative=True)
|
| 154 |
+
assert B(1 + nn, 2 + nn)**B(1, 2) == B(1 + nn, (2 + nn)**2)
|
| 155 |
+
i = Symbol('i', integer=True, negative=True)
|
| 156 |
+
assert B(1, 2)**i == B(2**i, 1)
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def test_AccumBounds_pow():
|
| 160 |
+
assert B(0, 2)**2 == B(0, 4)
|
| 161 |
+
assert B(-1, 1)**2 == B(0, 1)
|
| 162 |
+
assert B(1, 2)**2 == B(1, 4)
|
| 163 |
+
assert B(-1, 2)**3 == B(-1, 8)
|
| 164 |
+
assert B(-1, 1)**0 == 1
|
| 165 |
+
|
| 166 |
+
assert B(1, 2)**Rational(5, 2) == B(1, 4*sqrt(2))
|
| 167 |
+
assert B(0, 2)**S.Half == B(0, sqrt(2))
|
| 168 |
+
|
| 169 |
+
neg = Symbol('neg', negative=True)
|
| 170 |
+
assert unchanged(Pow, B(neg, 1), S.Half)
|
| 171 |
+
nn = Symbol('nn', nonnegative=True)
|
| 172 |
+
assert B(nn, nn + 1)**S.Half == B(sqrt(nn), sqrt(nn + 1))
|
| 173 |
+
assert B(nn, nn + 1)**nn == B(nn**nn, (nn + 1)**nn)
|
| 174 |
+
assert unchanged(Pow, B(nn, nn + 1), x)
|
| 175 |
+
i = Symbol('i', integer=True)
|
| 176 |
+
assert B(1, 2)**i == B(Min(1, 2**i), Max(1, 2**i))
|
| 177 |
+
i = Symbol('i', integer=True, nonnegative=True)
|
| 178 |
+
assert B(1, 2)**i == B(1, 2**i)
|
| 179 |
+
assert B(0, 1)**i == B(0**i, 1)
|
| 180 |
+
|
| 181 |
+
assert B(1, 5)**(-2) == B(Rational(1, 25), 1)
|
| 182 |
+
assert B(-1, 3)**(-2) == B(0, oo)
|
| 183 |
+
assert B(0, 2)**(-3) == B(Rational(1, 8), oo)
|
| 184 |
+
assert B(-2, 0)**(-3) == B(-oo, -Rational(1, 8))
|
| 185 |
+
assert B(0, 2)**(-2) == B(Rational(1, 4), oo)
|
| 186 |
+
assert B(-1, 2)**(-3) == B(-oo, oo)
|
| 187 |
+
assert B(-3, -2)**(-3) == B(Rational(-1, 8), Rational(-1, 27))
|
| 188 |
+
assert B(-3, -2)**(-2) == B(Rational(1, 9), Rational(1, 4))
|
| 189 |
+
assert B(0, oo)**S.Half == B(0, oo)
|
| 190 |
+
assert B(-oo, 0)**(-2) == B(0, oo)
|
| 191 |
+
assert B(-2, 0)**(-2) == B(Rational(1, 4), oo)
|
| 192 |
+
|
| 193 |
+
assert B(Rational(1, 3), S.Half)**oo is S.Zero
|
| 194 |
+
assert B(0, S.Half)**oo is S.Zero
|
| 195 |
+
assert B(S.Half, 1)**oo == B(0, oo)
|
| 196 |
+
assert B(0, 1)**oo == B(0, oo)
|
| 197 |
+
assert B(2, 3)**oo is oo
|
| 198 |
+
assert B(1, 2)**oo == B(0, oo)
|
| 199 |
+
assert B(S.Half, 3)**oo == B(0, oo)
|
| 200 |
+
assert B(Rational(-1, 3), Rational(-1, 4))**oo is S.Zero
|
| 201 |
+
assert B(-1, Rational(-1, 2))**oo is S.NaN
|
| 202 |
+
assert B(-3, -2)**oo is zoo
|
| 203 |
+
assert B(-2, -1)**oo is S.NaN
|
| 204 |
+
assert B(-2, Rational(-1, 2))**oo is S.NaN
|
| 205 |
+
assert B(Rational(-1, 2), S.Half)**oo is S.Zero
|
| 206 |
+
assert B(Rational(-1, 2), 1)**oo == B(0, oo)
|
| 207 |
+
assert B(Rational(-2, 3), 2)**oo == B(0, oo)
|
| 208 |
+
assert B(-1, 1)**oo == B(-oo, oo)
|
| 209 |
+
assert B(-1, S.Half)**oo == B(-oo, oo)
|
| 210 |
+
assert B(-1, 2)**oo == B(-oo, oo)
|
| 211 |
+
assert B(-2, S.Half)**oo == B(-oo, oo)
|
| 212 |
+
|
| 213 |
+
assert B(1, 2)**x == Pow(B(1, 2), x, evaluate=False)
|
| 214 |
+
|
| 215 |
+
assert B(2, 3)**(-oo) is S.Zero
|
| 216 |
+
assert B(0, 2)**(-oo) == B(0, oo)
|
| 217 |
+
assert B(-1, 2)**(-oo) == B(-oo, oo)
|
| 218 |
+
|
| 219 |
+
assert (tan(x)**sin(2*x)).subs(x, B(0, pi/2)) == \
|
| 220 |
+
Pow(B(-oo, oo), B(0, 1))
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
def test_AccumBounds_exponent():
|
| 224 |
+
# base is 0
|
| 225 |
+
z = 0**B(a, a + S.Half)
|
| 226 |
+
assert z.subs(a, 0) == B(0, 1)
|
| 227 |
+
assert z.subs(a, 1) == 0
|
| 228 |
+
p = z.subs(a, -1)
|
| 229 |
+
assert p.is_Pow and p.args == (0, B(-1, -S.Half))
|
| 230 |
+
# base > 0
|
| 231 |
+
# when base is 1 the type of bounds does not matter
|
| 232 |
+
assert 1**B(a, a + 1) == 1
|
| 233 |
+
# otherwise we need to know if 0 is in the bounds
|
| 234 |
+
assert S.Half**B(-2, 2) == B(S(1)/4, 4)
|
| 235 |
+
assert 2**B(-2, 2) == B(S(1)/4, 4)
|
| 236 |
+
|
| 237 |
+
# +eps may introduce +oo
|
| 238 |
+
# if there is a negative integer exponent
|
| 239 |
+
assert B(0, 1)**B(S(1)/2, 1) == B(0, 1)
|
| 240 |
+
assert B(0, 1)**B(0, 1) == B(0, 1)
|
| 241 |
+
|
| 242 |
+
# positive bases have positive bounds
|
| 243 |
+
assert B(2, 3)**B(-3, -2) == B(S(1)/27, S(1)/4)
|
| 244 |
+
assert B(2, 3)**B(-3, 2) == B(S(1)/27, 9)
|
| 245 |
+
|
| 246 |
+
# bounds generating imaginary parts unevaluated
|
| 247 |
+
assert unchanged(Pow, B(-1, 1), B(1, 2))
|
| 248 |
+
assert B(0, S(1)/2)**B(1, oo) == B(0, S(1)/2)
|
| 249 |
+
assert B(0, 1)**B(1, oo) == B(0, oo)
|
| 250 |
+
assert B(0, 2)**B(1, oo) == B(0, oo)
|
| 251 |
+
assert B(0, oo)**B(1, oo) == B(0, oo)
|
| 252 |
+
assert B(S(1)/2, 1)**B(1, oo) == B(0, oo)
|
| 253 |
+
assert B(S(1)/2, 1)**B(-oo, -1) == B(0, oo)
|
| 254 |
+
assert B(S(1)/2, 1)**B(-oo, oo) == B(0, oo)
|
| 255 |
+
assert B(S(1)/2, 2)**B(1, oo) == B(0, oo)
|
| 256 |
+
assert B(S(1)/2, 2)**B(-oo, -1) == B(0, oo)
|
| 257 |
+
assert B(S(1)/2, 2)**B(-oo, oo) == B(0, oo)
|
| 258 |
+
assert B(S(1)/2, oo)**B(1, oo) == B(0, oo)
|
| 259 |
+
assert B(S(1)/2, oo)**B(-oo, -1) == B(0, oo)
|
| 260 |
+
assert B(S(1)/2, oo)**B(-oo, oo) == B(0, oo)
|
| 261 |
+
assert B(1, 2)**B(1, oo) == B(0, oo)
|
| 262 |
+
assert B(1, 2)**B(-oo, -1) == B(0, oo)
|
| 263 |
+
assert B(1, 2)**B(-oo, oo) == B(0, oo)
|
| 264 |
+
assert B(1, oo)**B(1, oo) == B(0, oo)
|
| 265 |
+
assert B(1, oo)**B(-oo, -1) == B(0, oo)
|
| 266 |
+
assert B(1, oo)**B(-oo, oo) == B(0, oo)
|
| 267 |
+
assert B(2, oo)**B(1, oo) == B(2, oo)
|
| 268 |
+
assert B(2, oo)**B(-oo, -1) == B(0, S(1)/2)
|
| 269 |
+
assert B(2, oo)**B(-oo, oo) == B(0, oo)
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
def test_comparison_AccumBounds():
|
| 273 |
+
assert (B(1, 3) < 4) == S.true
|
| 274 |
+
assert (B(1, 3) < -1) == S.false
|
| 275 |
+
assert (B(1, 3) < 2).rel_op == '<'
|
| 276 |
+
assert (B(1, 3) <= 2).rel_op == '<='
|
| 277 |
+
|
| 278 |
+
assert (B(1, 3) > 4) == S.false
|
| 279 |
+
assert (B(1, 3) > -1) == S.true
|
| 280 |
+
assert (B(1, 3) > 2).rel_op == '>'
|
| 281 |
+
assert (B(1, 3) >= 2).rel_op == '>='
|
| 282 |
+
|
| 283 |
+
assert (B(1, 3) < B(4, 6)) == S.true
|
| 284 |
+
assert (B(1, 3) < B(2, 4)).rel_op == '<'
|
| 285 |
+
assert (B(1, 3) < B(-2, 0)) == S.false
|
| 286 |
+
|
| 287 |
+
assert (B(1, 3) <= B(4, 6)) == S.true
|
| 288 |
+
assert (B(1, 3) <= B(-2, 0)) == S.false
|
| 289 |
+
|
| 290 |
+
assert (B(1, 3) > B(4, 6)) == S.false
|
| 291 |
+
assert (B(1, 3) > B(-2, 0)) == S.true
|
| 292 |
+
|
| 293 |
+
assert (B(1, 3) >= B(4, 6)) == S.false
|
| 294 |
+
assert (B(1, 3) >= B(-2, 0)) == S.true
|
| 295 |
+
|
| 296 |
+
# issue 13499
|
| 297 |
+
assert (cos(x) > 0).subs(x, oo) == (B(-1, 1) > 0)
|
| 298 |
+
|
| 299 |
+
c = Symbol('c')
|
| 300 |
+
raises(TypeError, lambda: (B(0, 1) < c))
|
| 301 |
+
raises(TypeError, lambda: (B(0, 1) <= c))
|
| 302 |
+
raises(TypeError, lambda: (B(0, 1) > c))
|
| 303 |
+
raises(TypeError, lambda: (B(0, 1) >= c))
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
def test_contains_AccumBounds():
|
| 307 |
+
assert (1 in B(1, 2)) == S.true
|
| 308 |
+
raises(TypeError, lambda: a in B(1, 2))
|
| 309 |
+
assert 0 in B(-1, 0)
|
| 310 |
+
raises(TypeError, lambda:
|
| 311 |
+
(cos(1)**2 + sin(1)**2 - 1) in B(-1, 0))
|
| 312 |
+
assert (-oo in B(1, oo)) == S.true
|
| 313 |
+
assert (oo in B(-oo, 0)) == S.true
|
| 314 |
+
|
| 315 |
+
# issue 13159
|
| 316 |
+
assert Mul(0, B(-1, 1)) == Mul(B(-1, 1), 0) == 0
|
| 317 |
+
import itertools
|
| 318 |
+
for perm in itertools.permutations([0, B(-1, 1), x]):
|
| 319 |
+
assert Mul(*perm) == 0
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
def test_intersection_AccumBounds():
|
| 323 |
+
assert B(0, 3).intersection(B(1, 2)) == B(1, 2)
|
| 324 |
+
assert B(0, 3).intersection(B(1, 4)) == B(1, 3)
|
| 325 |
+
assert B(0, 3).intersection(B(-1, 2)) == B(0, 2)
|
| 326 |
+
assert B(0, 3).intersection(B(-1, 4)) == B(0, 3)
|
| 327 |
+
assert B(0, 1).intersection(B(2, 3)) == S.EmptySet
|
| 328 |
+
raises(TypeError, lambda: B(0, 3).intersection(1))
|
| 329 |
+
|
| 330 |
+
|
| 331 |
+
def test_union_AccumBounds():
|
| 332 |
+
assert B(0, 3).union(B(1, 2)) == B(0, 3)
|
| 333 |
+
assert B(0, 3).union(B(1, 4)) == B(0, 4)
|
| 334 |
+
assert B(0, 3).union(B(-1, 2)) == B(-1, 3)
|
| 335 |
+
assert B(0, 3).union(B(-1, 4)) == B(-1, 4)
|
| 336 |
+
raises(TypeError, lambda: B(0, 3).union(1))
|
infer_4_47_1/lib/python3.10/site-packages/sympy/calculus/tests/test_euler.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.core.function import (Derivative as D, Function)
|
| 2 |
+
from sympy.core.relational import Eq
|
| 3 |
+
from sympy.core.symbol import (Symbol, symbols)
|
| 4 |
+
from sympy.functions.elementary.trigonometric import (cos, sin)
|
| 5 |
+
from sympy.testing.pytest import raises
|
| 6 |
+
from sympy.calculus.euler import euler_equations as euler
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def test_euler_interface():
|
| 10 |
+
x = Function('x')
|
| 11 |
+
y = Symbol('y')
|
| 12 |
+
t = Symbol('t')
|
| 13 |
+
raises(TypeError, lambda: euler())
|
| 14 |
+
raises(TypeError, lambda: euler(D(x(t), t)*y(t), [x(t), y]))
|
| 15 |
+
raises(ValueError, lambda: euler(D(x(t), t)*x(y), [x(t), x(y)]))
|
| 16 |
+
raises(TypeError, lambda: euler(D(x(t), t)**2, x(0)))
|
| 17 |
+
raises(TypeError, lambda: euler(D(x(t), t)*y(t), [t]))
|
| 18 |
+
assert euler(D(x(t), t)**2/2, {x(t)}) == [Eq(-D(x(t), t, t), 0)]
|
| 19 |
+
assert euler(D(x(t), t)**2/2, x(t), {t}) == [Eq(-D(x(t), t, t), 0)]
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def test_euler_pendulum():
|
| 23 |
+
x = Function('x')
|
| 24 |
+
t = Symbol('t')
|
| 25 |
+
L = D(x(t), t)**2/2 + cos(x(t))
|
| 26 |
+
assert euler(L, x(t), t) == [Eq(-sin(x(t)) - D(x(t), t, t), 0)]
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def test_euler_henonheiles():
|
| 30 |
+
x = Function('x')
|
| 31 |
+
y = Function('y')
|
| 32 |
+
t = Symbol('t')
|
| 33 |
+
L = sum(D(z(t), t)**2/2 - z(t)**2/2 for z in [x, y])
|
| 34 |
+
L += -x(t)**2*y(t) + y(t)**3/3
|
| 35 |
+
assert euler(L, [x(t), y(t)], t) == [Eq(-2*x(t)*y(t) - x(t) -
|
| 36 |
+
D(x(t), t, t), 0),
|
| 37 |
+
Eq(-x(t)**2 + y(t)**2 -
|
| 38 |
+
y(t) - D(y(t), t, t), 0)]
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def test_euler_sineg():
|
| 42 |
+
psi = Function('psi')
|
| 43 |
+
t = Symbol('t')
|
| 44 |
+
x = Symbol('x')
|
| 45 |
+
L = D(psi(t, x), t)**2/2 - D(psi(t, x), x)**2/2 + cos(psi(t, x))
|
| 46 |
+
assert euler(L, psi(t, x), [t, x]) == [Eq(-sin(psi(t, x)) -
|
| 47 |
+
D(psi(t, x), t, t) +
|
| 48 |
+
D(psi(t, x), x, x), 0)]
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def test_euler_high_order():
|
| 52 |
+
# an example from hep-th/0309038
|
| 53 |
+
m = Symbol('m')
|
| 54 |
+
k = Symbol('k')
|
| 55 |
+
x = Function('x')
|
| 56 |
+
y = Function('y')
|
| 57 |
+
t = Symbol('t')
|
| 58 |
+
L = (m*D(x(t), t)**2/2 + m*D(y(t), t)**2/2 -
|
| 59 |
+
k*D(x(t), t)*D(y(t), t, t) + k*D(y(t), t)*D(x(t), t, t))
|
| 60 |
+
assert euler(L, [x(t), y(t)]) == [Eq(2*k*D(y(t), t, t, t) -
|
| 61 |
+
m*D(x(t), t, t), 0),
|
| 62 |
+
Eq(-2*k*D(x(t), t, t, t) -
|
| 63 |
+
m*D(y(t), t, t), 0)]
|
| 64 |
+
|
| 65 |
+
w = Symbol('w')
|
| 66 |
+
L = D(x(t, w), t, w)**2/2
|
| 67 |
+
assert euler(L) == [Eq(D(x(t, w), t, t, w, w), 0)]
|
| 68 |
+
|
| 69 |
+
def test_issue_18653():
|
| 70 |
+
x, y, z = symbols("x y z")
|
| 71 |
+
f, g, h = symbols("f g h", cls=Function, args=(x, y))
|
| 72 |
+
f, g, h = f(), g(), h()
|
| 73 |
+
expr2 = f.diff(x)*h.diff(z)
|
| 74 |
+
assert euler(expr2, (f,), (x, y)) == []
|
infer_4_47_1/lib/python3.10/site-packages/sympy/calculus/tests/test_finite_diff.py
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from itertools import product
|
| 2 |
+
|
| 3 |
+
from sympy.core.function import (Function, diff)
|
| 4 |
+
from sympy.core.numbers import Rational
|
| 5 |
+
from sympy.core.singleton import S
|
| 6 |
+
from sympy.core.symbol import symbols
|
| 7 |
+
from sympy.functions.elementary.exponential import exp
|
| 8 |
+
from sympy.calculus.finite_diff import (
|
| 9 |
+
apply_finite_diff, differentiate_finite, finite_diff_weights,
|
| 10 |
+
_as_finite_diff
|
| 11 |
+
)
|
| 12 |
+
from sympy.testing.pytest import raises, warns_deprecated_sympy
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def test_apply_finite_diff():
|
| 16 |
+
x, h = symbols('x h')
|
| 17 |
+
f = Function('f')
|
| 18 |
+
assert (apply_finite_diff(1, [x-h, x+h], [f(x-h), f(x+h)], x) -
|
| 19 |
+
(f(x+h)-f(x-h))/(2*h)).simplify() == 0
|
| 20 |
+
|
| 21 |
+
assert (apply_finite_diff(1, [5, 6, 7], [f(5), f(6), f(7)], 5) -
|
| 22 |
+
(Rational(-3, 2)*f(5) + 2*f(6) - S.Half*f(7))).simplify() == 0
|
| 23 |
+
raises(ValueError, lambda: apply_finite_diff(1, [x, h], [f(x)]))
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def test_finite_diff_weights():
|
| 27 |
+
|
| 28 |
+
d = finite_diff_weights(1, [5, 6, 7], 5)
|
| 29 |
+
assert d[1][2] == [Rational(-3, 2), 2, Rational(-1, 2)]
|
| 30 |
+
|
| 31 |
+
# Table 1, p. 702 in doi:10.1090/S0025-5718-1988-0935077-0
|
| 32 |
+
# --------------------------------------------------------
|
| 33 |
+
xl = [0, 1, -1, 2, -2, 3, -3, 4, -4]
|
| 34 |
+
|
| 35 |
+
# d holds all coefficients
|
| 36 |
+
d = finite_diff_weights(4, xl, S.Zero)
|
| 37 |
+
|
| 38 |
+
# Zeroeth derivative
|
| 39 |
+
for i in range(5):
|
| 40 |
+
assert d[0][i] == [S.One] + [S.Zero]*8
|
| 41 |
+
|
| 42 |
+
# First derivative
|
| 43 |
+
assert d[1][0] == [S.Zero]*9
|
| 44 |
+
assert d[1][2] == [S.Zero, S.Half, Rational(-1, 2)] + [S.Zero]*6
|
| 45 |
+
assert d[1][4] == [S.Zero, Rational(2, 3), Rational(-2, 3), Rational(-1, 12), Rational(1, 12)] + [S.Zero]*4
|
| 46 |
+
assert d[1][6] == [S.Zero, Rational(3, 4), Rational(-3, 4), Rational(-3, 20), Rational(3, 20),
|
| 47 |
+
Rational(1, 60), Rational(-1, 60)] + [S.Zero]*2
|
| 48 |
+
assert d[1][8] == [S.Zero, Rational(4, 5), Rational(-4, 5), Rational(-1, 5), Rational(1, 5),
|
| 49 |
+
Rational(4, 105), Rational(-4, 105), Rational(-1, 280), Rational(1, 280)]
|
| 50 |
+
|
| 51 |
+
# Second derivative
|
| 52 |
+
for i in range(2):
|
| 53 |
+
assert d[2][i] == [S.Zero]*9
|
| 54 |
+
assert d[2][2] == [-S(2), S.One, S.One] + [S.Zero]*6
|
| 55 |
+
assert d[2][4] == [Rational(-5, 2), Rational(4, 3), Rational(4, 3), Rational(-1, 12), Rational(-1, 12)] + [S.Zero]*4
|
| 56 |
+
assert d[2][6] == [Rational(-49, 18), Rational(3, 2), Rational(3, 2), Rational(-3, 20), Rational(-3, 20),
|
| 57 |
+
Rational(1, 90), Rational(1, 90)] + [S.Zero]*2
|
| 58 |
+
assert d[2][8] == [Rational(-205, 72), Rational(8, 5), Rational(8, 5), Rational(-1, 5), Rational(-1, 5),
|
| 59 |
+
Rational(8, 315), Rational(8, 315), Rational(-1, 560), Rational(-1, 560)]
|
| 60 |
+
|
| 61 |
+
# Third derivative
|
| 62 |
+
for i in range(3):
|
| 63 |
+
assert d[3][i] == [S.Zero]*9
|
| 64 |
+
assert d[3][4] == [S.Zero, -S.One, S.One, S.Half, Rational(-1, 2)] + [S.Zero]*4
|
| 65 |
+
assert d[3][6] == [S.Zero, Rational(-13, 8), Rational(13, 8), S.One, -S.One,
|
| 66 |
+
Rational(-1, 8), Rational(1, 8)] + [S.Zero]*2
|
| 67 |
+
assert d[3][8] == [S.Zero, Rational(-61, 30), Rational(61, 30), Rational(169, 120), Rational(-169, 120),
|
| 68 |
+
Rational(-3, 10), Rational(3, 10), Rational(7, 240), Rational(-7, 240)]
|
| 69 |
+
|
| 70 |
+
# Fourth derivative
|
| 71 |
+
for i in range(4):
|
| 72 |
+
assert d[4][i] == [S.Zero]*9
|
| 73 |
+
assert d[4][4] == [S(6), -S(4), -S(4), S.One, S.One] + [S.Zero]*4
|
| 74 |
+
assert d[4][6] == [Rational(28, 3), Rational(-13, 2), Rational(-13, 2), S(2), S(2),
|
| 75 |
+
Rational(-1, 6), Rational(-1, 6)] + [S.Zero]*2
|
| 76 |
+
assert d[4][8] == [Rational(91, 8), Rational(-122, 15), Rational(-122, 15), Rational(169, 60), Rational(169, 60),
|
| 77 |
+
Rational(-2, 5), Rational(-2, 5), Rational(7, 240), Rational(7, 240)]
|
| 78 |
+
|
| 79 |
+
# Table 2, p. 703 in doi:10.1090/S0025-5718-1988-0935077-0
|
| 80 |
+
# --------------------------------------------------------
|
| 81 |
+
xl = [[j/S(2) for j in list(range(-i*2+1, 0, 2))+list(range(1, i*2+1, 2))]
|
| 82 |
+
for i in range(1, 5)]
|
| 83 |
+
|
| 84 |
+
# d holds all coefficients
|
| 85 |
+
d = [finite_diff_weights({0: 1, 1: 2, 2: 4, 3: 4}[i], xl[i], 0) for
|
| 86 |
+
i in range(4)]
|
| 87 |
+
|
| 88 |
+
# Zeroth derivative
|
| 89 |
+
assert d[0][0][1] == [S.Half, S.Half]
|
| 90 |
+
assert d[1][0][3] == [Rational(-1, 16), Rational(9, 16), Rational(9, 16), Rational(-1, 16)]
|
| 91 |
+
assert d[2][0][5] == [Rational(3, 256), Rational(-25, 256), Rational(75, 128), Rational(75, 128),
|
| 92 |
+
Rational(-25, 256), Rational(3, 256)]
|
| 93 |
+
assert d[3][0][7] == [Rational(-5, 2048), Rational(49, 2048), Rational(-245, 2048), Rational(1225, 2048),
|
| 94 |
+
Rational(1225, 2048), Rational(-245, 2048), Rational(49, 2048), Rational(-5, 2048)]
|
| 95 |
+
|
| 96 |
+
# First derivative
|
| 97 |
+
assert d[0][1][1] == [-S.One, S.One]
|
| 98 |
+
assert d[1][1][3] == [Rational(1, 24), Rational(-9, 8), Rational(9, 8), Rational(-1, 24)]
|
| 99 |
+
assert d[2][1][5] == [Rational(-3, 640), Rational(25, 384), Rational(-75, 64),
|
| 100 |
+
Rational(75, 64), Rational(-25, 384), Rational(3, 640)]
|
| 101 |
+
assert d[3][1][7] == [Rational(5, 7168), Rational(-49, 5120),
|
| 102 |
+
Rational(245, 3072), Rational(-1225, 1024),
|
| 103 |
+
Rational(1225, 1024), Rational(-245, 3072),
|
| 104 |
+
Rational(49, 5120), Rational(-5, 7168)]
|
| 105 |
+
|
| 106 |
+
# Reasonably the rest of the table is also correct... (testing of that
|
| 107 |
+
# deemed excessive at the moment)
|
| 108 |
+
raises(ValueError, lambda: finite_diff_weights(-1, [1, 2]))
|
| 109 |
+
raises(ValueError, lambda: finite_diff_weights(1.2, [1, 2]))
|
| 110 |
+
x = symbols('x')
|
| 111 |
+
raises(ValueError, lambda: finite_diff_weights(x, [1, 2]))
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def test_as_finite_diff():
|
| 115 |
+
x = symbols('x')
|
| 116 |
+
f = Function('f')
|
| 117 |
+
dx = Function('dx')
|
| 118 |
+
|
| 119 |
+
_as_finite_diff(f(x).diff(x), [x-2, x-1, x, x+1, x+2])
|
| 120 |
+
|
| 121 |
+
# Use of undefined functions in ``points``
|
| 122 |
+
df_true = -f(x+dx(x)/2-dx(x+dx(x)/2)/2) / dx(x+dx(x)/2) \
|
| 123 |
+
+ f(x+dx(x)/2+dx(x+dx(x)/2)/2) / dx(x+dx(x)/2)
|
| 124 |
+
df_test = diff(f(x), x).as_finite_difference(points=dx(x), x0=x+dx(x)/2)
|
| 125 |
+
assert (df_test - df_true).simplify() == 0
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def test_differentiate_finite():
|
| 129 |
+
x, y, h = symbols('x y h')
|
| 130 |
+
f = Function('f')
|
| 131 |
+
with warns_deprecated_sympy():
|
| 132 |
+
res0 = differentiate_finite(f(x, y) + exp(42), x, y, evaluate=True)
|
| 133 |
+
xm, xp, ym, yp = [v + sign*S.Half for v, sign in product([x, y], [-1, 1])]
|
| 134 |
+
ref0 = f(xm, ym) + f(xp, yp) - f(xm, yp) - f(xp, ym)
|
| 135 |
+
assert (res0 - ref0).simplify() == 0
|
| 136 |
+
|
| 137 |
+
g = Function('g')
|
| 138 |
+
with warns_deprecated_sympy():
|
| 139 |
+
res1 = differentiate_finite(f(x)*g(x) + 42, x, evaluate=True)
|
| 140 |
+
ref1 = (-f(x - S.Half) + f(x + S.Half))*g(x) + \
|
| 141 |
+
(-g(x - S.Half) + g(x + S.Half))*f(x)
|
| 142 |
+
assert (res1 - ref1).simplify() == 0
|
| 143 |
+
|
| 144 |
+
res2 = differentiate_finite(f(x) + x**3 + 42, x, points=[x-1, x+1])
|
| 145 |
+
ref2 = (f(x + 1) + (x + 1)**3 - f(x - 1) - (x - 1)**3)/2
|
| 146 |
+
assert (res2 - ref2).simplify() == 0
|
| 147 |
+
raises(TypeError, lambda: differentiate_finite(f(x)*g(x), x,
|
| 148 |
+
pints=[x-1, x+1]))
|
| 149 |
+
|
| 150 |
+
res3 = differentiate_finite(f(x)*g(x).diff(x), x)
|
| 151 |
+
ref3 = (-g(x) + g(x + 1))*f(x + S.Half) - (g(x) - g(x - 1))*f(x - S.Half)
|
| 152 |
+
assert res3 == ref3
|
| 153 |
+
|
| 154 |
+
res4 = differentiate_finite(f(x)*g(x).diff(x).diff(x), x)
|
| 155 |
+
ref4 = -((g(x - Rational(3, 2)) - 2*g(x - S.Half) + g(x + S.Half))*f(x - S.Half)) \
|
| 156 |
+
+ (g(x - S.Half) - 2*g(x + S.Half) + g(x + Rational(3, 2)))*f(x + S.Half)
|
| 157 |
+
assert res4 == ref4
|
| 158 |
+
|
| 159 |
+
res5_expr = f(x).diff(x)*g(x).diff(x)
|
| 160 |
+
res5 = differentiate_finite(res5_expr, points=[x-h, x, x+h])
|
| 161 |
+
ref5 = (-2*f(x)/h + f(-h + x)/(2*h) + 3*f(h + x)/(2*h))*(-2*g(x)/h + g(-h + x)/(2*h) \
|
| 162 |
+
+ 3*g(h + x)/(2*h))/(2*h) - (2*f(x)/h - 3*f(-h + x)/(2*h) - \
|
| 163 |
+
f(h + x)/(2*h))*(2*g(x)/h - 3*g(-h + x)/(2*h) - g(h + x)/(2*h))/(2*h)
|
| 164 |
+
assert res5 == ref5
|
| 165 |
+
|
| 166 |
+
res6 = res5.limit(h, 0).doit()
|
| 167 |
+
ref6 = diff(res5_expr, x)
|
| 168 |
+
assert res6 == ref6
|
infer_4_47_1/lib/python3.10/site-packages/sympy/calculus/tests/test_singularities.py
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.core.numbers import (I, Rational, pi, oo)
|
| 2 |
+
from sympy.core.singleton import S
|
| 3 |
+
from sympy.core.symbol import Symbol, Dummy
|
| 4 |
+
from sympy.core.function import Lambda
|
| 5 |
+
from sympy.functions.elementary.exponential import (exp, log)
|
| 6 |
+
from sympy.functions.elementary.trigonometric import sec, csc
|
| 7 |
+
from sympy.functions.elementary.hyperbolic import (coth, sech,
|
| 8 |
+
atanh, asech, acoth, acsch)
|
| 9 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
| 10 |
+
from sympy.calculus.singularities import (
|
| 11 |
+
singularities,
|
| 12 |
+
is_increasing,
|
| 13 |
+
is_strictly_increasing,
|
| 14 |
+
is_decreasing,
|
| 15 |
+
is_strictly_decreasing,
|
| 16 |
+
is_monotonic
|
| 17 |
+
)
|
| 18 |
+
from sympy.sets import Interval, FiniteSet, Union, ImageSet
|
| 19 |
+
from sympy.testing.pytest import raises
|
| 20 |
+
from sympy.abc import x, y
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def test_singularities():
|
| 24 |
+
x = Symbol('x')
|
| 25 |
+
assert singularities(x**2, x) == S.EmptySet
|
| 26 |
+
assert singularities(x/(x**2 + 3*x + 2), x) == FiniteSet(-2, -1)
|
| 27 |
+
assert singularities(1/(x**2 + 1), x) == FiniteSet(I, -I)
|
| 28 |
+
assert singularities(x/(x**3 + 1), x) == \
|
| 29 |
+
FiniteSet(-1, (1 - sqrt(3) * I) / 2, (1 + sqrt(3) * I) / 2)
|
| 30 |
+
assert singularities(1/(y**2 + 2*I*y + 1), y) == \
|
| 31 |
+
FiniteSet(-I + sqrt(2)*I, -I - sqrt(2)*I)
|
| 32 |
+
_n = Dummy('n')
|
| 33 |
+
assert singularities(sech(x), x).dummy_eq(Union(
|
| 34 |
+
ImageSet(Lambda(_n, 2*_n*I*pi + I*pi/2), S.Integers),
|
| 35 |
+
ImageSet(Lambda(_n, 2*_n*I*pi + 3*I*pi/2), S.Integers)))
|
| 36 |
+
assert singularities(coth(x), x).dummy_eq(Union(
|
| 37 |
+
ImageSet(Lambda(_n, 2*_n*I*pi + I*pi), S.Integers),
|
| 38 |
+
ImageSet(Lambda(_n, 2*_n*I*pi), S.Integers)))
|
| 39 |
+
assert singularities(atanh(x), x) == FiniteSet(-1, 1)
|
| 40 |
+
assert singularities(acoth(x), x) == FiniteSet(-1, 1)
|
| 41 |
+
assert singularities(asech(x), x) == FiniteSet(0)
|
| 42 |
+
assert singularities(acsch(x), x) == FiniteSet(0)
|
| 43 |
+
|
| 44 |
+
x = Symbol('x', real=True)
|
| 45 |
+
assert singularities(1/(x**2 + 1), x) == S.EmptySet
|
| 46 |
+
assert singularities(exp(1/x), x, S.Reals) == FiniteSet(0)
|
| 47 |
+
assert singularities(exp(1/x), x, Interval(1, 2)) == S.EmptySet
|
| 48 |
+
assert singularities(log((x - 2)**2), x, Interval(1, 3)) == FiniteSet(2)
|
| 49 |
+
raises(NotImplementedError, lambda: singularities(x**-oo, x))
|
| 50 |
+
assert singularities(sec(x), x, Interval(0, 3*pi)) == FiniteSet(
|
| 51 |
+
pi/2, 3*pi/2, 5*pi/2)
|
| 52 |
+
assert singularities(csc(x), x, Interval(0, 3*pi)) == FiniteSet(
|
| 53 |
+
0, pi, 2*pi, 3*pi)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def test_is_increasing():
|
| 57 |
+
"""Test whether is_increasing returns correct value."""
|
| 58 |
+
a = Symbol('a', negative=True)
|
| 59 |
+
|
| 60 |
+
assert is_increasing(x**3 - 3*x**2 + 4*x, S.Reals)
|
| 61 |
+
assert is_increasing(-x**2, Interval(-oo, 0))
|
| 62 |
+
assert not is_increasing(-x**2, Interval(0, oo))
|
| 63 |
+
assert not is_increasing(4*x**3 - 6*x**2 - 72*x + 30, Interval(-2, 3))
|
| 64 |
+
assert is_increasing(x**2 + y, Interval(1, oo), x)
|
| 65 |
+
assert is_increasing(-x**2*a, Interval(1, oo), x)
|
| 66 |
+
assert is_increasing(1)
|
| 67 |
+
|
| 68 |
+
assert is_increasing(4*x**3 - 6*x**2 - 72*x + 30, Interval(-2, 3)) is False
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def test_is_strictly_increasing():
|
| 72 |
+
"""Test whether is_strictly_increasing returns correct value."""
|
| 73 |
+
assert is_strictly_increasing(
|
| 74 |
+
4*x**3 - 6*x**2 - 72*x + 30, Interval.Ropen(-oo, -2))
|
| 75 |
+
assert is_strictly_increasing(
|
| 76 |
+
4*x**3 - 6*x**2 - 72*x + 30, Interval.Lopen(3, oo))
|
| 77 |
+
assert not is_strictly_increasing(
|
| 78 |
+
4*x**3 - 6*x**2 - 72*x + 30, Interval.open(-2, 3))
|
| 79 |
+
assert not is_strictly_increasing(-x**2, Interval(0, oo))
|
| 80 |
+
assert not is_strictly_decreasing(1)
|
| 81 |
+
|
| 82 |
+
assert is_strictly_increasing(4*x**3 - 6*x**2 - 72*x + 30, Interval.open(-2, 3)) is False
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def test_is_decreasing():
|
| 86 |
+
"""Test whether is_decreasing returns correct value."""
|
| 87 |
+
b = Symbol('b', positive=True)
|
| 88 |
+
|
| 89 |
+
assert is_decreasing(1/(x**2 - 3*x), Interval.open(Rational(3,2), 3))
|
| 90 |
+
assert is_decreasing(1/(x**2 - 3*x), Interval.open(1.5, 3))
|
| 91 |
+
assert is_decreasing(1/(x**2 - 3*x), Interval.Lopen(3, oo))
|
| 92 |
+
assert not is_decreasing(1/(x**2 - 3*x), Interval.Ropen(-oo, Rational(3, 2)))
|
| 93 |
+
assert not is_decreasing(-x**2, Interval(-oo, 0))
|
| 94 |
+
assert not is_decreasing(-x**2*b, Interval(-oo, 0), x)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def test_is_strictly_decreasing():
|
| 98 |
+
"""Test whether is_strictly_decreasing returns correct value."""
|
| 99 |
+
assert is_strictly_decreasing(1/(x**2 - 3*x), Interval.Lopen(3, oo))
|
| 100 |
+
assert not is_strictly_decreasing(
|
| 101 |
+
1/(x**2 - 3*x), Interval.Ropen(-oo, Rational(3, 2)))
|
| 102 |
+
assert not is_strictly_decreasing(-x**2, Interval(-oo, 0))
|
| 103 |
+
assert not is_strictly_decreasing(1)
|
| 104 |
+
assert is_strictly_decreasing(1/(x**2 - 3*x), Interval.open(Rational(3,2), 3))
|
| 105 |
+
assert is_strictly_decreasing(1/(x**2 - 3*x), Interval.open(1.5, 3))
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def test_is_monotonic():
|
| 109 |
+
"""Test whether is_monotonic returns correct value."""
|
| 110 |
+
assert is_monotonic(1/(x**2 - 3*x), Interval.open(Rational(3,2), 3))
|
| 111 |
+
assert is_monotonic(1/(x**2 - 3*x), Interval.open(1.5, 3))
|
| 112 |
+
assert is_monotonic(1/(x**2 - 3*x), Interval.Lopen(3, oo))
|
| 113 |
+
assert is_monotonic(x**3 - 3*x**2 + 4*x, S.Reals)
|
| 114 |
+
assert not is_monotonic(-x**2, S.Reals)
|
| 115 |
+
assert is_monotonic(x**2 + y + 1, Interval(1, 2), x)
|
| 116 |
+
raises(NotImplementedError, lambda: is_monotonic(x**2 + y + 1))
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def test_issue_23401():
|
| 120 |
+
x = Symbol('x')
|
| 121 |
+
expr = (x + 1)/(-1.0e-3*x**2 + 0.1*x + 0.1)
|
| 122 |
+
assert is_increasing(expr, Interval(1,2), x)
|
infer_4_47_1/lib/python3.10/site-packages/sympy/calculus/tests/test_util.py
ADDED
|
@@ -0,0 +1,392 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.core.function import Lambda
|
| 2 |
+
from sympy.core.numbers import (E, I, Rational, oo, pi)
|
| 3 |
+
from sympy.core.relational import Eq
|
| 4 |
+
from sympy.core.singleton import S
|
| 5 |
+
from sympy.core.symbol import (Dummy, Symbol)
|
| 6 |
+
from sympy.functions.elementary.complexes import (Abs, re)
|
| 7 |
+
from sympy.functions.elementary.exponential import (exp, log)
|
| 8 |
+
from sympy.functions.elementary.integers import frac
|
| 9 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
| 10 |
+
from sympy.functions.elementary.piecewise import Piecewise
|
| 11 |
+
from sympy.functions.elementary.trigonometric import (
|
| 12 |
+
cos, cot, csc, sec, sin, tan, asin, acos, atan, acot, asec, acsc)
|
| 13 |
+
from sympy.functions.elementary.hyperbolic import (sinh, cosh, tanh, coth,
|
| 14 |
+
sech, csch, asinh, acosh, atanh, acoth, asech, acsch)
|
| 15 |
+
from sympy.functions.special.gamma_functions import gamma
|
| 16 |
+
from sympy.functions.special.error_functions import expint
|
| 17 |
+
from sympy.matrices.expressions.matexpr import MatrixSymbol
|
| 18 |
+
from sympy.simplify.simplify import simplify
|
| 19 |
+
from sympy.calculus.util import (function_range, continuous_domain, not_empty_in,
|
| 20 |
+
periodicity, lcim, is_convex,
|
| 21 |
+
stationary_points, minimum, maximum)
|
| 22 |
+
from sympy.sets.sets import (Interval, FiniteSet, Complement, Union)
|
| 23 |
+
from sympy.sets.fancysets import ImageSet
|
| 24 |
+
from sympy.sets.conditionset import ConditionSet
|
| 25 |
+
from sympy.testing.pytest import XFAIL, raises, _both_exp_pow, slow
|
| 26 |
+
from sympy.abc import x, y
|
| 27 |
+
|
| 28 |
+
a = Symbol('a', real=True)
|
| 29 |
+
|
| 30 |
+
def test_function_range():
|
| 31 |
+
assert function_range(sin(x), x, Interval(-pi/2, pi/2)
|
| 32 |
+
) == Interval(-1, 1)
|
| 33 |
+
assert function_range(sin(x), x, Interval(0, pi)
|
| 34 |
+
) == Interval(0, 1)
|
| 35 |
+
assert function_range(tan(x), x, Interval(0, pi)
|
| 36 |
+
) == Interval(-oo, oo)
|
| 37 |
+
assert function_range(tan(x), x, Interval(pi/2, pi)
|
| 38 |
+
) == Interval(-oo, 0)
|
| 39 |
+
assert function_range((x + 3)/(x - 2), x, Interval(-5, 5)
|
| 40 |
+
) == Union(Interval(-oo, Rational(2, 7)), Interval(Rational(8, 3), oo))
|
| 41 |
+
assert function_range(1/(x**2), x, Interval(-1, 1)
|
| 42 |
+
) == Interval(1, oo)
|
| 43 |
+
assert function_range(exp(x), x, Interval(-1, 1)
|
| 44 |
+
) == Interval(exp(-1), exp(1))
|
| 45 |
+
assert function_range(log(x) - x, x, S.Reals
|
| 46 |
+
) == Interval(-oo, -1)
|
| 47 |
+
assert function_range(sqrt(3*x - 1), x, Interval(0, 2)
|
| 48 |
+
) == Interval(0, sqrt(5))
|
| 49 |
+
assert function_range(x*(x - 1) - (x**2 - x), x, S.Reals
|
| 50 |
+
) == FiniteSet(0)
|
| 51 |
+
assert function_range(x*(x - 1) - (x**2 - x) + y, x, S.Reals
|
| 52 |
+
) == FiniteSet(y)
|
| 53 |
+
assert function_range(sin(x), x, Union(Interval(-5, -3), FiniteSet(4))
|
| 54 |
+
) == Union(Interval(-sin(3), 1), FiniteSet(sin(4)))
|
| 55 |
+
assert function_range(cos(x), x, Interval(-oo, -4)
|
| 56 |
+
) == Interval(-1, 1)
|
| 57 |
+
assert function_range(cos(x), x, S.EmptySet) == S.EmptySet
|
| 58 |
+
assert function_range(x/sqrt(x**2+1), x, S.Reals) == Interval.open(-1,1)
|
| 59 |
+
raises(NotImplementedError, lambda : function_range(
|
| 60 |
+
exp(x)*(sin(x) - cos(x))/2 - x, x, S.Reals))
|
| 61 |
+
raises(NotImplementedError, lambda : function_range(
|
| 62 |
+
sin(x) + x, x, S.Reals)) # issue 13273
|
| 63 |
+
raises(NotImplementedError, lambda : function_range(
|
| 64 |
+
log(x), x, S.Integers))
|
| 65 |
+
raises(NotImplementedError, lambda : function_range(
|
| 66 |
+
sin(x)/2, x, S.Naturals))
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
@slow
|
| 70 |
+
def test_function_range1():
|
| 71 |
+
assert function_range(tan(x)**2 + tan(3*x)**2 + 1, x, S.Reals) == Interval(1,oo)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def test_continuous_domain():
|
| 75 |
+
assert continuous_domain(sin(x), x, Interval(0, 2*pi)) == Interval(0, 2*pi)
|
| 76 |
+
assert continuous_domain(tan(x), x, Interval(0, 2*pi)) == \
|
| 77 |
+
Union(Interval(0, pi/2, False, True), Interval(pi/2, pi*Rational(3, 2), True, True),
|
| 78 |
+
Interval(pi*Rational(3, 2), 2*pi, True, False))
|
| 79 |
+
assert continuous_domain(cot(x), x, Interval(0, 2*pi)) == Union(
|
| 80 |
+
Interval.open(0, pi), Interval.open(pi, 2*pi))
|
| 81 |
+
assert continuous_domain((x - 1)/((x - 1)**2), x, S.Reals) == \
|
| 82 |
+
Union(Interval(-oo, 1, True, True), Interval(1, oo, True, True))
|
| 83 |
+
assert continuous_domain(log(x) + log(4*x - 1), x, S.Reals) == \
|
| 84 |
+
Interval(Rational(1, 4), oo, True, True)
|
| 85 |
+
assert continuous_domain(1/sqrt(x - 3), x, S.Reals) == Interval(3, oo, True, True)
|
| 86 |
+
assert continuous_domain(1/x - 2, x, S.Reals) == \
|
| 87 |
+
Union(Interval.open(-oo, 0), Interval.open(0, oo))
|
| 88 |
+
assert continuous_domain(1/(x**2 - 4) + 2, x, S.Reals) == \
|
| 89 |
+
Union(Interval.open(-oo, -2), Interval.open(-2, 2), Interval.open(2, oo))
|
| 90 |
+
assert continuous_domain((x+1)**pi, x, S.Reals) == Interval(-1, oo)
|
| 91 |
+
assert continuous_domain((x+1)**(pi/2), x, S.Reals) == Interval(-1, oo)
|
| 92 |
+
assert continuous_domain(x**x, x, S.Reals) == Interval(0, oo)
|
| 93 |
+
assert continuous_domain((x+1)**log(x**2), x, S.Reals) == Union(
|
| 94 |
+
Interval.Ropen(-1, 0), Interval.open(0, oo))
|
| 95 |
+
domain = continuous_domain(log(tan(x)**2 + 1), x, S.Reals)
|
| 96 |
+
assert not domain.contains(3*pi/2)
|
| 97 |
+
assert domain.contains(5)
|
| 98 |
+
d = Symbol('d', even=True, zero=False)
|
| 99 |
+
assert continuous_domain(x**(1/d), x, S.Reals) == Interval(0, oo)
|
| 100 |
+
n = Dummy('n')
|
| 101 |
+
assert continuous_domain(1/sin(x), x, S.Reals).dummy_eq(Complement(
|
| 102 |
+
S.Reals, Union(ImageSet(Lambda(n, 2*n*pi + pi), S.Integers),
|
| 103 |
+
ImageSet(Lambda(n, 2*n*pi), S.Integers))))
|
| 104 |
+
assert continuous_domain(sin(x) + cos(x), x, S.Reals) == S.Reals
|
| 105 |
+
assert continuous_domain(asin(x), x, S.Reals) == Interval(-1, 1) # issue #21786
|
| 106 |
+
assert continuous_domain(1/acos(log(x)), x, S.Reals) == Interval.Ropen(exp(-1), E)
|
| 107 |
+
assert continuous_domain(sinh(x)+cosh(x), x, S.Reals) == S.Reals
|
| 108 |
+
assert continuous_domain(tanh(x)+sech(x), x, S.Reals) == S.Reals
|
| 109 |
+
assert continuous_domain(atan(x)+asinh(x), x, S.Reals) == S.Reals
|
| 110 |
+
assert continuous_domain(acosh(x), x, S.Reals) == Interval(1, oo)
|
| 111 |
+
assert continuous_domain(atanh(x), x, S.Reals) == Interval.open(-1, 1)
|
| 112 |
+
assert continuous_domain(atanh(x)+acosh(x), x, S.Reals) == S.EmptySet
|
| 113 |
+
assert continuous_domain(asech(x), x, S.Reals) == Interval.Lopen(0, 1)
|
| 114 |
+
assert continuous_domain(acoth(x), x, S.Reals) == Union(
|
| 115 |
+
Interval.open(-oo, -1), Interval.open(1, oo))
|
| 116 |
+
assert continuous_domain(asec(x), x, S.Reals) == Union(
|
| 117 |
+
Interval(-oo, -1), Interval(1, oo))
|
| 118 |
+
assert continuous_domain(acsc(x), x, S.Reals) == Union(
|
| 119 |
+
Interval(-oo, -1), Interval(1, oo))
|
| 120 |
+
for f in (coth, acsch, csch):
|
| 121 |
+
assert continuous_domain(f(x), x, S.Reals) == Union(
|
| 122 |
+
Interval.open(-oo, 0), Interval.open(0, oo))
|
| 123 |
+
assert continuous_domain(acot(x), x, S.Reals).contains(0) == False
|
| 124 |
+
assert continuous_domain(1/(exp(x) - x), x, S.Reals) == Complement(
|
| 125 |
+
S.Reals, ConditionSet(x, Eq(-x + exp(x), 0), S.Reals))
|
| 126 |
+
assert continuous_domain(frac(x**2), x, Interval(-2,-1)) == Union(
|
| 127 |
+
Interval.open(-2, -sqrt(3)), Interval.open(-sqrt(2), -1),
|
| 128 |
+
Interval.open(-sqrt(3), -sqrt(2)))
|
| 129 |
+
assert continuous_domain(frac(x), x, S.Reals) == Complement(
|
| 130 |
+
S.Reals, S.Integers)
|
| 131 |
+
raises(NotImplementedError, lambda : continuous_domain(
|
| 132 |
+
1/(x**2+1), x, S.Complexes))
|
| 133 |
+
raises(NotImplementedError, lambda : continuous_domain(
|
| 134 |
+
gamma(x), x, Interval(-5,0)))
|
| 135 |
+
assert continuous_domain(x + gamma(pi), x, S.Reals) == S.Reals
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
@XFAIL
|
| 139 |
+
def test_continuous_domain_acot():
|
| 140 |
+
acot_cont = Piecewise((pi+acot(x), x<0), (acot(x), True))
|
| 141 |
+
assert continuous_domain(acot_cont, x, S.Reals) == S.Reals
|
| 142 |
+
|
| 143 |
+
@XFAIL
|
| 144 |
+
def test_continuous_domain_gamma():
|
| 145 |
+
assert continuous_domain(gamma(x), x, S.Reals).contains(-1) == False
|
| 146 |
+
|
| 147 |
+
@XFAIL
|
| 148 |
+
def test_continuous_domain_neg_power():
|
| 149 |
+
assert continuous_domain((x-2)**(1-x), x, S.Reals) == Interval.open(2, oo)
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def test_not_empty_in():
|
| 153 |
+
assert not_empty_in(FiniteSet(x, 2*x).intersect(Interval(1, 2, True, False)), x) == \
|
| 154 |
+
Interval(S.Half, 2, True, False)
|
| 155 |
+
assert not_empty_in(FiniteSet(x, x**2).intersect(Interval(1, 2)), x) == \
|
| 156 |
+
Union(Interval(-sqrt(2), -1), Interval(1, 2))
|
| 157 |
+
assert not_empty_in(FiniteSet(x**2 + x, x).intersect(Interval(2, 4)), x) == \
|
| 158 |
+
Union(Interval(-sqrt(17)/2 - S.Half, -2),
|
| 159 |
+
Interval(1, Rational(-1, 2) + sqrt(17)/2), Interval(2, 4))
|
| 160 |
+
assert not_empty_in(FiniteSet(x/(x - 1)).intersect(S.Reals), x) == \
|
| 161 |
+
Complement(S.Reals, FiniteSet(1))
|
| 162 |
+
assert not_empty_in(FiniteSet(a/(a - 1)).intersect(S.Reals), a) == \
|
| 163 |
+
Complement(S.Reals, FiniteSet(1))
|
| 164 |
+
assert not_empty_in(FiniteSet((x**2 - 3*x + 2)/(x - 1)).intersect(S.Reals), x) == \
|
| 165 |
+
Complement(S.Reals, FiniteSet(1))
|
| 166 |
+
assert not_empty_in(FiniteSet(3, 4, x/(x - 1)).intersect(Interval(2, 3)), x) == \
|
| 167 |
+
Interval(-oo, oo)
|
| 168 |
+
assert not_empty_in(FiniteSet(4, x/(x - 1)).intersect(Interval(2, 3)), x) == \
|
| 169 |
+
Interval(S(3)/2, 2)
|
| 170 |
+
assert not_empty_in(FiniteSet(x/(x**2 - 1)).intersect(S.Reals), x) == \
|
| 171 |
+
Complement(S.Reals, FiniteSet(-1, 1))
|
| 172 |
+
assert not_empty_in(FiniteSet(x, x**2).intersect(Union(Interval(1, 3, True, True),
|
| 173 |
+
Interval(4, 5))), x) == \
|
| 174 |
+
Union(Interval(-sqrt(5), -2), Interval(-sqrt(3), -1, True, True),
|
| 175 |
+
Interval(1, 3, True, True), Interval(4, 5))
|
| 176 |
+
assert not_empty_in(FiniteSet(1).intersect(Interval(3, 4)), x) == S.EmptySet
|
| 177 |
+
assert not_empty_in(FiniteSet(x**2/(x + 2)).intersect(Interval(1, oo)), x) == \
|
| 178 |
+
Union(Interval(-2, -1, True, False), Interval(2, oo))
|
| 179 |
+
raises(ValueError, lambda: not_empty_in(x))
|
| 180 |
+
raises(ValueError, lambda: not_empty_in(Interval(0, 1), x))
|
| 181 |
+
raises(NotImplementedError,
|
| 182 |
+
lambda: not_empty_in(FiniteSet(x).intersect(S.Reals), x, a))
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
@_both_exp_pow
|
| 186 |
+
def test_periodicity():
|
| 187 |
+
assert periodicity(sin(2*x), x) == pi
|
| 188 |
+
assert periodicity((-2)*tan(4*x), x) == pi/4
|
| 189 |
+
assert periodicity(sin(x)**2, x) == 2*pi
|
| 190 |
+
assert periodicity(3**tan(3*x), x) == pi/3
|
| 191 |
+
assert periodicity(tan(x)*cos(x), x) == 2*pi
|
| 192 |
+
assert periodicity(sin(x)**(tan(x)), x) == 2*pi
|
| 193 |
+
assert periodicity(tan(x)*sec(x), x) == 2*pi
|
| 194 |
+
assert periodicity(sin(2*x)*cos(2*x) - y, x) == pi/2
|
| 195 |
+
assert periodicity(tan(x) + cot(x), x) == pi
|
| 196 |
+
assert periodicity(sin(x) - cos(2*x), x) == 2*pi
|
| 197 |
+
assert periodicity(sin(x) - 1, x) == 2*pi
|
| 198 |
+
assert periodicity(sin(4*x) + sin(x)*cos(x), x) == pi
|
| 199 |
+
assert periodicity(exp(sin(x)), x) == 2*pi
|
| 200 |
+
assert periodicity(log(cot(2*x)) - sin(cos(2*x)), x) == pi
|
| 201 |
+
assert periodicity(sin(2*x)*exp(tan(x) - csc(2*x)), x) == pi
|
| 202 |
+
assert periodicity(cos(sec(x) - csc(2*x)), x) == 2*pi
|
| 203 |
+
assert periodicity(tan(sin(2*x)), x) == pi
|
| 204 |
+
assert periodicity(2*tan(x)**2, x) == pi
|
| 205 |
+
assert periodicity(sin(x%4), x) == 4
|
| 206 |
+
assert periodicity(sin(x)%4, x) == 2*pi
|
| 207 |
+
assert periodicity(tan((3*x-2)%4), x) == Rational(4, 3)
|
| 208 |
+
assert periodicity((sqrt(2)*(x+1)+x) % 3, x) == 3 / (sqrt(2)+1)
|
| 209 |
+
assert periodicity((x**2+1) % x, x) is None
|
| 210 |
+
assert periodicity(sin(re(x)), x) == 2*pi
|
| 211 |
+
assert periodicity(sin(x)**2 + cos(x)**2, x) is S.Zero
|
| 212 |
+
assert periodicity(tan(x), y) is S.Zero
|
| 213 |
+
assert periodicity(sin(x) + I*cos(x), x) == 2*pi
|
| 214 |
+
assert periodicity(x - sin(2*y), y) == pi
|
| 215 |
+
|
| 216 |
+
assert periodicity(exp(x), x) is None
|
| 217 |
+
assert periodicity(exp(I*x), x) == 2*pi
|
| 218 |
+
assert periodicity(exp(I*a), a) == 2*pi
|
| 219 |
+
assert periodicity(exp(a), a) is None
|
| 220 |
+
assert periodicity(exp(log(sin(a) + I*cos(2*a)), evaluate=False), a) == 2*pi
|
| 221 |
+
assert periodicity(exp(log(sin(2*a) + I*cos(a)), evaluate=False), a) == 2*pi
|
| 222 |
+
assert periodicity(exp(sin(a)), a) == 2*pi
|
| 223 |
+
assert periodicity(exp(2*I*a), a) == pi
|
| 224 |
+
assert periodicity(exp(a + I*sin(a)), a) is None
|
| 225 |
+
assert periodicity(exp(cos(a/2) + sin(a)), a) == 4*pi
|
| 226 |
+
assert periodicity(log(x), x) is None
|
| 227 |
+
assert periodicity(exp(x)**sin(x), x) is None
|
| 228 |
+
assert periodicity(sin(x)**y, y) is None
|
| 229 |
+
|
| 230 |
+
assert periodicity(Abs(sin(Abs(sin(x)))), x) == pi
|
| 231 |
+
assert all(periodicity(Abs(f(x)), x) == pi for f in (
|
| 232 |
+
cos, sin, sec, csc, tan, cot))
|
| 233 |
+
assert periodicity(Abs(sin(tan(x))), x) == pi
|
| 234 |
+
assert periodicity(Abs(sin(sin(x) + tan(x))), x) == 2*pi
|
| 235 |
+
assert periodicity(sin(x) > S.Half, x) == 2*pi
|
| 236 |
+
|
| 237 |
+
assert periodicity(x > 2, x) is None
|
| 238 |
+
assert periodicity(x**3 - x**2 + 1, x) is None
|
| 239 |
+
assert periodicity(Abs(x), x) is None
|
| 240 |
+
assert periodicity(Abs(x**2 - 1), x) is None
|
| 241 |
+
|
| 242 |
+
assert periodicity((x**2 + 4)%2, x) is None
|
| 243 |
+
assert periodicity((E**x)%3, x) is None
|
| 244 |
+
|
| 245 |
+
assert periodicity(sin(expint(1, x))/expint(1, x), x) is None
|
| 246 |
+
# returning `None` for any Piecewise
|
| 247 |
+
p = Piecewise((0, x < -1), (x**2, x <= 1), (log(x), True))
|
| 248 |
+
assert periodicity(p, x) is None
|
| 249 |
+
|
| 250 |
+
m = MatrixSymbol('m', 3, 3)
|
| 251 |
+
raises(NotImplementedError, lambda: periodicity(sin(m), m))
|
| 252 |
+
raises(NotImplementedError, lambda: periodicity(sin(m[0, 0]), m))
|
| 253 |
+
raises(NotImplementedError, lambda: periodicity(sin(m), m[0, 0]))
|
| 254 |
+
raises(NotImplementedError, lambda: periodicity(sin(m[0, 0]), m[0, 0]))
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
def test_periodicity_check():
|
| 258 |
+
assert periodicity(tan(x), x, check=True) == pi
|
| 259 |
+
assert periodicity(sin(x) + cos(x), x, check=True) == 2*pi
|
| 260 |
+
assert periodicity(sec(x), x) == 2*pi
|
| 261 |
+
assert periodicity(sin(x*y), x) == 2*pi/abs(y)
|
| 262 |
+
assert periodicity(Abs(sec(sec(x))), x) == pi
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
def test_lcim():
|
| 266 |
+
assert lcim([S.Half, S(2), S(3)]) == 6
|
| 267 |
+
assert lcim([pi/2, pi/4, pi]) == pi
|
| 268 |
+
assert lcim([2*pi, pi/2]) == 2*pi
|
| 269 |
+
assert lcim([S.One, 2*pi]) is None
|
| 270 |
+
assert lcim([S(2) + 2*E, E/3 + Rational(1, 3), S.One + E]) == S(2) + 2*E
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
def test_is_convex():
|
| 274 |
+
assert is_convex(1/x, x, domain=Interval.open(0, oo)) == True
|
| 275 |
+
assert is_convex(1/x, x, domain=Interval(-oo, 0)) == False
|
| 276 |
+
assert is_convex(x**2, x, domain=Interval(0, oo)) == True
|
| 277 |
+
assert is_convex(1/x**3, x, domain=Interval.Lopen(0, oo)) == True
|
| 278 |
+
assert is_convex(-1/x**3, x, domain=Interval.Ropen(-oo, 0)) == True
|
| 279 |
+
assert is_convex(log(x) ,x) == False
|
| 280 |
+
assert is_convex(x**2+y**2, x, y) == True
|
| 281 |
+
assert is_convex(cos(x) + cos(y), x) == False
|
| 282 |
+
assert is_convex(8*x**2 - 2*y**2, x, y) == False
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
def test_stationary_points():
|
| 286 |
+
assert stationary_points(sin(x), x, Interval(-pi/2, pi/2)
|
| 287 |
+
) == {-pi/2, pi/2}
|
| 288 |
+
assert stationary_points(sin(x), x, Interval.Ropen(0, pi/4)
|
| 289 |
+
) is S.EmptySet
|
| 290 |
+
assert stationary_points(tan(x), x,
|
| 291 |
+
) is S.EmptySet
|
| 292 |
+
assert stationary_points(sin(x)*cos(x), x, Interval(0, pi)
|
| 293 |
+
) == {pi/4, pi*Rational(3, 4)}
|
| 294 |
+
assert stationary_points(sec(x), x, Interval(0, pi)
|
| 295 |
+
) == {0, pi}
|
| 296 |
+
assert stationary_points((x+3)*(x-2), x
|
| 297 |
+
) == FiniteSet(Rational(-1, 2))
|
| 298 |
+
assert stationary_points((x + 3)/(x - 2), x, Interval(-5, 5)
|
| 299 |
+
) is S.EmptySet
|
| 300 |
+
assert stationary_points((x**2+3)/(x-2), x
|
| 301 |
+
) == {2 - sqrt(7), 2 + sqrt(7)}
|
| 302 |
+
assert stationary_points((x**2+3)/(x-2), x, Interval(0, 5)
|
| 303 |
+
) == {2 + sqrt(7)}
|
| 304 |
+
assert stationary_points(x**4 + x**3 - 5*x**2, x, S.Reals
|
| 305 |
+
) == FiniteSet(-2, 0, Rational(5, 4))
|
| 306 |
+
assert stationary_points(exp(x), x
|
| 307 |
+
) is S.EmptySet
|
| 308 |
+
assert stationary_points(log(x) - x, x, S.Reals
|
| 309 |
+
) == {1}
|
| 310 |
+
assert stationary_points(cos(x), x, Union(Interval(0, 5), Interval(-6, -3))
|
| 311 |
+
) == {0, -pi, pi}
|
| 312 |
+
assert stationary_points(y, x, S.Reals
|
| 313 |
+
) == S.Reals
|
| 314 |
+
assert stationary_points(y, x, S.EmptySet) == S.EmptySet
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
def test_maximum():
|
| 318 |
+
assert maximum(sin(x), x) is S.One
|
| 319 |
+
assert maximum(sin(x), x, Interval(0, 1)) == sin(1)
|
| 320 |
+
assert maximum(tan(x), x) is oo
|
| 321 |
+
assert maximum(tan(x), x, Interval(-pi/4, pi/4)) is S.One
|
| 322 |
+
assert maximum(sin(x)*cos(x), x, S.Reals) == S.Half
|
| 323 |
+
assert simplify(maximum(sin(x)*cos(x), x, Interval(pi*Rational(3, 8), pi*Rational(5, 8)))
|
| 324 |
+
) == sqrt(2)/4
|
| 325 |
+
assert maximum((x+3)*(x-2), x) is oo
|
| 326 |
+
assert maximum((x+3)*(x-2), x, Interval(-5, 0)) == S(14)
|
| 327 |
+
assert maximum((x+3)/(x-2), x, Interval(-5, 0)) == Rational(2, 7)
|
| 328 |
+
assert simplify(maximum(-x**4-x**3+x**2+10, x)
|
| 329 |
+
) == 41*sqrt(41)/512 + Rational(5419, 512)
|
| 330 |
+
assert maximum(exp(x), x, Interval(-oo, 2)) == exp(2)
|
| 331 |
+
assert maximum(log(x) - x, x, S.Reals) is S.NegativeOne
|
| 332 |
+
assert maximum(cos(x), x, Union(Interval(0, 5), Interval(-6, -3))
|
| 333 |
+
) is S.One
|
| 334 |
+
assert maximum(cos(x)-sin(x), x, S.Reals) == sqrt(2)
|
| 335 |
+
assert maximum(y, x, S.Reals) == y
|
| 336 |
+
assert maximum(abs(a**3 + a), a, Interval(0, 2)) == 10
|
| 337 |
+
assert maximum(abs(60*a**3 + 24*a), a, Interval(0, 2)) == 528
|
| 338 |
+
assert maximum(abs(12*a*(5*a**2 + 2)), a, Interval(0, 2)) == 528
|
| 339 |
+
assert maximum(x/sqrt(x**2+1), x, S.Reals) == 1
|
| 340 |
+
|
| 341 |
+
raises(ValueError, lambda : maximum(sin(x), x, S.EmptySet))
|
| 342 |
+
raises(ValueError, lambda : maximum(log(cos(x)), x, S.EmptySet))
|
| 343 |
+
raises(ValueError, lambda : maximum(1/(x**2 + y**2 + 1), x, S.EmptySet))
|
| 344 |
+
raises(ValueError, lambda : maximum(sin(x), sin(x)))
|
| 345 |
+
raises(ValueError, lambda : maximum(sin(x), x*y, S.EmptySet))
|
| 346 |
+
raises(ValueError, lambda : maximum(sin(x), S.One))
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
def test_minimum():
|
| 350 |
+
assert minimum(sin(x), x) is S.NegativeOne
|
| 351 |
+
assert minimum(sin(x), x, Interval(1, 4)) == sin(4)
|
| 352 |
+
assert minimum(tan(x), x) is -oo
|
| 353 |
+
assert minimum(tan(x), x, Interval(-pi/4, pi/4)) is S.NegativeOne
|
| 354 |
+
assert minimum(sin(x)*cos(x), x, S.Reals) == Rational(-1, 2)
|
| 355 |
+
assert simplify(minimum(sin(x)*cos(x), x, Interval(pi*Rational(3, 8), pi*Rational(5, 8)))
|
| 356 |
+
) == -sqrt(2)/4
|
| 357 |
+
assert minimum((x+3)*(x-2), x) == Rational(-25, 4)
|
| 358 |
+
assert minimum((x+3)/(x-2), x, Interval(-5, 0)) == Rational(-3, 2)
|
| 359 |
+
assert minimum(x**4-x**3+x**2+10, x) == S(10)
|
| 360 |
+
assert minimum(exp(x), x, Interval(-2, oo)) == exp(-2)
|
| 361 |
+
assert minimum(log(x) - x, x, S.Reals) is -oo
|
| 362 |
+
assert minimum(cos(x), x, Union(Interval(0, 5), Interval(-6, -3))
|
| 363 |
+
) is S.NegativeOne
|
| 364 |
+
assert minimum(cos(x)-sin(x), x, S.Reals) == -sqrt(2)
|
| 365 |
+
assert minimum(y, x, S.Reals) == y
|
| 366 |
+
assert minimum(x/sqrt(x**2+1), x, S.Reals) == -1
|
| 367 |
+
|
| 368 |
+
raises(ValueError, lambda : minimum(sin(x), x, S.EmptySet))
|
| 369 |
+
raises(ValueError, lambda : minimum(log(cos(x)), x, S.EmptySet))
|
| 370 |
+
raises(ValueError, lambda : minimum(1/(x**2 + y**2 + 1), x, S.EmptySet))
|
| 371 |
+
raises(ValueError, lambda : minimum(sin(x), sin(x)))
|
| 372 |
+
raises(ValueError, lambda : minimum(sin(x), x*y, S.EmptySet))
|
| 373 |
+
raises(ValueError, lambda : minimum(sin(x), S.One))
|
| 374 |
+
|
| 375 |
+
|
| 376 |
+
def test_issue_19869():
|
| 377 |
+
assert (maximum(sqrt(3)*(x - 1)/(3*sqrt(x**2 + 1)), x)
|
| 378 |
+
) == sqrt(3)/3
|
| 379 |
+
|
| 380 |
+
|
| 381 |
+
def test_issue_16469():
|
| 382 |
+
f = abs(a)
|
| 383 |
+
assert function_range(f, a, S.Reals) == Interval(0, oo, False, True)
|
| 384 |
+
|
| 385 |
+
|
| 386 |
+
@_both_exp_pow
|
| 387 |
+
def test_issue_18747():
|
| 388 |
+
assert periodicity(exp(pi*I*(x/4 + S.Half/2)), x) == 8
|
| 389 |
+
|
| 390 |
+
|
| 391 |
+
def test_issue_25942():
|
| 392 |
+
assert (acos(x) > pi/3).as_set() == Interval.Ropen(-1, S(1)/2)
|
infer_4_47_1/lib/python3.10/site-packages/sympy/calculus/util.py
ADDED
|
@@ -0,0 +1,905 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .accumulationbounds import AccumBounds, AccumulationBounds # noqa: F401
|
| 2 |
+
from .singularities import singularities
|
| 3 |
+
from sympy.core import Pow, S
|
| 4 |
+
from sympy.core.function import diff, expand_mul, Function
|
| 5 |
+
from sympy.core.kind import NumberKind
|
| 6 |
+
from sympy.core.mod import Mod
|
| 7 |
+
from sympy.core.numbers import equal_valued
|
| 8 |
+
from sympy.core.relational import Relational
|
| 9 |
+
from sympy.core.symbol import Symbol, Dummy
|
| 10 |
+
from sympy.core.sympify import _sympify
|
| 11 |
+
from sympy.functions.elementary.complexes import Abs, im, re
|
| 12 |
+
from sympy.functions.elementary.exponential import exp, log
|
| 13 |
+
from sympy.functions.elementary.integers import frac
|
| 14 |
+
from sympy.functions.elementary.piecewise import Piecewise
|
| 15 |
+
from sympy.functions.elementary.trigonometric import (
|
| 16 |
+
TrigonometricFunction, sin, cos, tan, cot, csc, sec,
|
| 17 |
+
asin, acos, acot, atan, asec, acsc)
|
| 18 |
+
from sympy.functions.elementary.hyperbolic import (sinh, cosh, tanh, coth,
|
| 19 |
+
sech, csch, asinh, acosh, atanh, acoth, asech, acsch)
|
| 20 |
+
from sympy.polys.polytools import degree, lcm_list
|
| 21 |
+
from sympy.sets.sets import (Interval, Intersection, FiniteSet, Union,
|
| 22 |
+
Complement)
|
| 23 |
+
from sympy.sets.fancysets import ImageSet
|
| 24 |
+
from sympy.sets.conditionset import ConditionSet
|
| 25 |
+
from sympy.utilities import filldedent
|
| 26 |
+
from sympy.utilities.iterables import iterable
|
| 27 |
+
from sympy.matrices.dense import hessian
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def continuous_domain(f, symbol, domain):
|
| 31 |
+
"""
|
| 32 |
+
Returns the domain on which the function expression f is continuous.
|
| 33 |
+
|
| 34 |
+
This function is limited by the ability to determine the various
|
| 35 |
+
singularities and discontinuities of the given function.
|
| 36 |
+
The result is either given as a union of intervals or constructed using
|
| 37 |
+
other set operations.
|
| 38 |
+
|
| 39 |
+
Parameters
|
| 40 |
+
==========
|
| 41 |
+
|
| 42 |
+
f : :py:class:`~.Expr`
|
| 43 |
+
The concerned function.
|
| 44 |
+
symbol : :py:class:`~.Symbol`
|
| 45 |
+
The variable for which the intervals are to be determined.
|
| 46 |
+
domain : :py:class:`~.Interval`
|
| 47 |
+
The domain over which the continuity of the symbol has to be checked.
|
| 48 |
+
|
| 49 |
+
Examples
|
| 50 |
+
========
|
| 51 |
+
|
| 52 |
+
>>> from sympy import Interval, Symbol, S, tan, log, pi, sqrt
|
| 53 |
+
>>> from sympy.calculus.util import continuous_domain
|
| 54 |
+
>>> x = Symbol('x')
|
| 55 |
+
>>> continuous_domain(1/x, x, S.Reals)
|
| 56 |
+
Union(Interval.open(-oo, 0), Interval.open(0, oo))
|
| 57 |
+
>>> continuous_domain(tan(x), x, Interval(0, pi))
|
| 58 |
+
Union(Interval.Ropen(0, pi/2), Interval.Lopen(pi/2, pi))
|
| 59 |
+
>>> continuous_domain(sqrt(x - 2), x, Interval(-5, 5))
|
| 60 |
+
Interval(2, 5)
|
| 61 |
+
>>> continuous_domain(log(2*x - 1), x, S.Reals)
|
| 62 |
+
Interval.open(1/2, oo)
|
| 63 |
+
|
| 64 |
+
Returns
|
| 65 |
+
=======
|
| 66 |
+
|
| 67 |
+
:py:class:`~.Interval`
|
| 68 |
+
Union of all intervals where the function is continuous.
|
| 69 |
+
|
| 70 |
+
Raises
|
| 71 |
+
======
|
| 72 |
+
|
| 73 |
+
NotImplementedError
|
| 74 |
+
If the method to determine continuity of such a function
|
| 75 |
+
has not yet been developed.
|
| 76 |
+
|
| 77 |
+
"""
|
| 78 |
+
from sympy.solvers.inequalities import solve_univariate_inequality
|
| 79 |
+
|
| 80 |
+
if not domain.is_subset(S.Reals):
|
| 81 |
+
raise NotImplementedError(filldedent('''
|
| 82 |
+
Domain must be a subset of S.Reals.
|
| 83 |
+
'''))
|
| 84 |
+
implemented = [Pow, exp, log, Abs, frac,
|
| 85 |
+
sin, cos, tan, cot, sec, csc,
|
| 86 |
+
asin, acos, atan, acot, asec, acsc,
|
| 87 |
+
sinh, cosh, tanh, coth, sech, csch,
|
| 88 |
+
asinh, acosh, atanh, acoth, asech, acsch]
|
| 89 |
+
used = [fct.func for fct in f.atoms(Function) if fct.has(symbol)]
|
| 90 |
+
if any(func not in implemented for func in used):
|
| 91 |
+
raise NotImplementedError(filldedent('''
|
| 92 |
+
Unable to determine the domain of the given function.
|
| 93 |
+
'''))
|
| 94 |
+
|
| 95 |
+
x = Symbol('x')
|
| 96 |
+
constraints = {
|
| 97 |
+
log: (x > 0,),
|
| 98 |
+
asin: (x >= -1, x <= 1),
|
| 99 |
+
acos: (x >= -1, x <= 1),
|
| 100 |
+
acosh: (x >= 1,),
|
| 101 |
+
atanh: (x > -1, x < 1),
|
| 102 |
+
asech: (x > 0, x <= 1)
|
| 103 |
+
}
|
| 104 |
+
constraints_union = {
|
| 105 |
+
asec: (x <= -1, x >= 1),
|
| 106 |
+
acsc: (x <= -1, x >= 1),
|
| 107 |
+
acoth: (x < -1, x > 1)
|
| 108 |
+
}
|
| 109 |
+
|
| 110 |
+
cont_domain = domain
|
| 111 |
+
for atom in f.atoms(Pow):
|
| 112 |
+
den = atom.exp.as_numer_denom()[1]
|
| 113 |
+
if atom.exp.is_rational and den.is_odd:
|
| 114 |
+
pass # 0**negative handled by singularities()
|
| 115 |
+
else:
|
| 116 |
+
constraint = solve_univariate_inequality(atom.base >= 0,
|
| 117 |
+
symbol).as_set()
|
| 118 |
+
cont_domain = Intersection(constraint, cont_domain)
|
| 119 |
+
|
| 120 |
+
for atom in f.atoms(Function):
|
| 121 |
+
if atom.func in constraints:
|
| 122 |
+
for c in constraints[atom.func]:
|
| 123 |
+
constraint_relational = c.subs(x, atom.args[0])
|
| 124 |
+
constraint_set = solve_univariate_inequality(
|
| 125 |
+
constraint_relational, symbol).as_set()
|
| 126 |
+
cont_domain = Intersection(constraint_set, cont_domain)
|
| 127 |
+
elif atom.func in constraints_union:
|
| 128 |
+
constraint_set = S.EmptySet
|
| 129 |
+
for c in constraints_union[atom.func]:
|
| 130 |
+
constraint_relational = c.subs(x, atom.args[0])
|
| 131 |
+
constraint_set += solve_univariate_inequality(
|
| 132 |
+
constraint_relational, symbol).as_set()
|
| 133 |
+
cont_domain = Intersection(constraint_set, cont_domain)
|
| 134 |
+
# XXX: the discontinuities below could be factored out in
|
| 135 |
+
# a new "discontinuities()".
|
| 136 |
+
elif atom.func == acot:
|
| 137 |
+
from sympy.solvers.solveset import solveset_real
|
| 138 |
+
# Sympy's acot() has a step discontinuity at 0. Since it's
|
| 139 |
+
# neither an essential singularity nor a pole, singularities()
|
| 140 |
+
# will not report it. But it's still relevant for determining
|
| 141 |
+
# the continuity of the function f.
|
| 142 |
+
cont_domain -= solveset_real(atom.args[0], symbol)
|
| 143 |
+
# Note that the above may introduce spurious discontinuities, e.g.
|
| 144 |
+
# for abs(acot(x)) at 0.
|
| 145 |
+
elif atom.func == frac:
|
| 146 |
+
from sympy.solvers.solveset import solveset_real
|
| 147 |
+
r = function_range(atom.args[0], symbol, domain)
|
| 148 |
+
r = Intersection(r, S.Integers)
|
| 149 |
+
if r.is_finite_set:
|
| 150 |
+
discont = S.EmptySet
|
| 151 |
+
for n in r:
|
| 152 |
+
discont += solveset_real(atom.args[0]-n, symbol)
|
| 153 |
+
else:
|
| 154 |
+
discont = ConditionSet(
|
| 155 |
+
symbol, S.Integers.contains(atom.args[0]), cont_domain)
|
| 156 |
+
cont_domain -= discont
|
| 157 |
+
|
| 158 |
+
return cont_domain - singularities(f, symbol, domain)
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def function_range(f, symbol, domain):
|
| 162 |
+
"""
|
| 163 |
+
Finds the range of a function in a given domain.
|
| 164 |
+
This method is limited by the ability to determine the singularities and
|
| 165 |
+
determine limits.
|
| 166 |
+
|
| 167 |
+
Parameters
|
| 168 |
+
==========
|
| 169 |
+
|
| 170 |
+
f : :py:class:`~.Expr`
|
| 171 |
+
The concerned function.
|
| 172 |
+
symbol : :py:class:`~.Symbol`
|
| 173 |
+
The variable for which the range of function is to be determined.
|
| 174 |
+
domain : :py:class:`~.Interval`
|
| 175 |
+
The domain under which the range of the function has to be found.
|
| 176 |
+
|
| 177 |
+
Examples
|
| 178 |
+
========
|
| 179 |
+
|
| 180 |
+
>>> from sympy import Interval, Symbol, S, exp, log, pi, sqrt, sin, tan
|
| 181 |
+
>>> from sympy.calculus.util import function_range
|
| 182 |
+
>>> x = Symbol('x')
|
| 183 |
+
>>> function_range(sin(x), x, Interval(0, 2*pi))
|
| 184 |
+
Interval(-1, 1)
|
| 185 |
+
>>> function_range(tan(x), x, Interval(-pi/2, pi/2))
|
| 186 |
+
Interval(-oo, oo)
|
| 187 |
+
>>> function_range(1/x, x, S.Reals)
|
| 188 |
+
Union(Interval.open(-oo, 0), Interval.open(0, oo))
|
| 189 |
+
>>> function_range(exp(x), x, S.Reals)
|
| 190 |
+
Interval.open(0, oo)
|
| 191 |
+
>>> function_range(log(x), x, S.Reals)
|
| 192 |
+
Interval(-oo, oo)
|
| 193 |
+
>>> function_range(sqrt(x), x, Interval(-5, 9))
|
| 194 |
+
Interval(0, 3)
|
| 195 |
+
|
| 196 |
+
Returns
|
| 197 |
+
=======
|
| 198 |
+
|
| 199 |
+
:py:class:`~.Interval`
|
| 200 |
+
Union of all ranges for all intervals under domain where function is
|
| 201 |
+
continuous.
|
| 202 |
+
|
| 203 |
+
Raises
|
| 204 |
+
======
|
| 205 |
+
|
| 206 |
+
NotImplementedError
|
| 207 |
+
If any of the intervals, in the given domain, for which function
|
| 208 |
+
is continuous are not finite or real,
|
| 209 |
+
OR if the critical points of the function on the domain cannot be found.
|
| 210 |
+
"""
|
| 211 |
+
|
| 212 |
+
if domain is S.EmptySet:
|
| 213 |
+
return S.EmptySet
|
| 214 |
+
|
| 215 |
+
period = periodicity(f, symbol)
|
| 216 |
+
if period == S.Zero:
|
| 217 |
+
# the expression is constant wrt symbol
|
| 218 |
+
return FiniteSet(f.expand())
|
| 219 |
+
|
| 220 |
+
from sympy.series.limits import limit
|
| 221 |
+
from sympy.solvers.solveset import solveset
|
| 222 |
+
|
| 223 |
+
if period is not None:
|
| 224 |
+
if isinstance(domain, Interval):
|
| 225 |
+
if (domain.inf - domain.sup).is_infinite:
|
| 226 |
+
domain = Interval(0, period)
|
| 227 |
+
elif isinstance(domain, Union):
|
| 228 |
+
for sub_dom in domain.args:
|
| 229 |
+
if isinstance(sub_dom, Interval) and \
|
| 230 |
+
((sub_dom.inf - sub_dom.sup).is_infinite):
|
| 231 |
+
domain = Interval(0, period)
|
| 232 |
+
|
| 233 |
+
intervals = continuous_domain(f, symbol, domain)
|
| 234 |
+
range_int = S.EmptySet
|
| 235 |
+
if isinstance(intervals,(Interval, FiniteSet)):
|
| 236 |
+
interval_iter = (intervals,)
|
| 237 |
+
|
| 238 |
+
elif isinstance(intervals, Union):
|
| 239 |
+
interval_iter = intervals.args
|
| 240 |
+
|
| 241 |
+
else:
|
| 242 |
+
raise NotImplementedError(filldedent('''
|
| 243 |
+
Unable to find range for the given domain.
|
| 244 |
+
'''))
|
| 245 |
+
|
| 246 |
+
for interval in interval_iter:
|
| 247 |
+
if isinstance(interval, FiniteSet):
|
| 248 |
+
for singleton in interval:
|
| 249 |
+
if singleton in domain:
|
| 250 |
+
range_int += FiniteSet(f.subs(symbol, singleton))
|
| 251 |
+
elif isinstance(interval, Interval):
|
| 252 |
+
vals = S.EmptySet
|
| 253 |
+
critical_points = S.EmptySet
|
| 254 |
+
critical_values = S.EmptySet
|
| 255 |
+
bounds = ((interval.left_open, interval.inf, '+'),
|
| 256 |
+
(interval.right_open, interval.sup, '-'))
|
| 257 |
+
|
| 258 |
+
for is_open, limit_point, direction in bounds:
|
| 259 |
+
if is_open:
|
| 260 |
+
critical_values += FiniteSet(limit(f, symbol, limit_point, direction))
|
| 261 |
+
vals += critical_values
|
| 262 |
+
|
| 263 |
+
else:
|
| 264 |
+
vals += FiniteSet(f.subs(symbol, limit_point))
|
| 265 |
+
|
| 266 |
+
solution = solveset(f.diff(symbol), symbol, interval)
|
| 267 |
+
|
| 268 |
+
if not iterable(solution):
|
| 269 |
+
raise NotImplementedError(
|
| 270 |
+
'Unable to find critical points for {}'.format(f))
|
| 271 |
+
if isinstance(solution, ImageSet):
|
| 272 |
+
raise NotImplementedError(
|
| 273 |
+
'Infinite number of critical points for {}'.format(f))
|
| 274 |
+
|
| 275 |
+
critical_points += solution
|
| 276 |
+
|
| 277 |
+
for critical_point in critical_points:
|
| 278 |
+
vals += FiniteSet(f.subs(symbol, critical_point))
|
| 279 |
+
|
| 280 |
+
left_open, right_open = False, False
|
| 281 |
+
|
| 282 |
+
if critical_values is not S.EmptySet:
|
| 283 |
+
if critical_values.inf == vals.inf:
|
| 284 |
+
left_open = True
|
| 285 |
+
|
| 286 |
+
if critical_values.sup == vals.sup:
|
| 287 |
+
right_open = True
|
| 288 |
+
|
| 289 |
+
range_int += Interval(vals.inf, vals.sup, left_open, right_open)
|
| 290 |
+
else:
|
| 291 |
+
raise NotImplementedError(filldedent('''
|
| 292 |
+
Unable to find range for the given domain.
|
| 293 |
+
'''))
|
| 294 |
+
|
| 295 |
+
return range_int
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
def not_empty_in(finset_intersection, *syms):
|
| 299 |
+
"""
|
| 300 |
+
Finds the domain of the functions in ``finset_intersection`` in which the
|
| 301 |
+
``finite_set`` is not-empty.
|
| 302 |
+
|
| 303 |
+
Parameters
|
| 304 |
+
==========
|
| 305 |
+
|
| 306 |
+
finset_intersection : Intersection of FiniteSet
|
| 307 |
+
The unevaluated intersection of FiniteSet containing
|
| 308 |
+
real-valued functions with Union of Sets
|
| 309 |
+
syms : Tuple of symbols
|
| 310 |
+
Symbol for which domain is to be found
|
| 311 |
+
|
| 312 |
+
Raises
|
| 313 |
+
======
|
| 314 |
+
|
| 315 |
+
NotImplementedError
|
| 316 |
+
The algorithms to find the non-emptiness of the given FiniteSet are
|
| 317 |
+
not yet implemented.
|
| 318 |
+
ValueError
|
| 319 |
+
The input is not valid.
|
| 320 |
+
RuntimeError
|
| 321 |
+
It is a bug, please report it to the github issue tracker
|
| 322 |
+
(https://github.com/sympy/sympy/issues).
|
| 323 |
+
|
| 324 |
+
Examples
|
| 325 |
+
========
|
| 326 |
+
|
| 327 |
+
>>> from sympy import FiniteSet, Interval, not_empty_in, oo
|
| 328 |
+
>>> from sympy.abc import x
|
| 329 |
+
>>> not_empty_in(FiniteSet(x/2).intersect(Interval(0, 1)), x)
|
| 330 |
+
Interval(0, 2)
|
| 331 |
+
>>> not_empty_in(FiniteSet(x, x**2).intersect(Interval(1, 2)), x)
|
| 332 |
+
Union(Interval(1, 2), Interval(-sqrt(2), -1))
|
| 333 |
+
>>> not_empty_in(FiniteSet(x**2/(x + 2)).intersect(Interval(1, oo)), x)
|
| 334 |
+
Union(Interval.Lopen(-2, -1), Interval(2, oo))
|
| 335 |
+
"""
|
| 336 |
+
|
| 337 |
+
# TODO: handle piecewise defined functions
|
| 338 |
+
# TODO: handle transcendental functions
|
| 339 |
+
# TODO: handle multivariate functions
|
| 340 |
+
if len(syms) == 0:
|
| 341 |
+
raise ValueError("One or more symbols must be given in syms.")
|
| 342 |
+
|
| 343 |
+
if finset_intersection is S.EmptySet:
|
| 344 |
+
return S.EmptySet
|
| 345 |
+
|
| 346 |
+
if isinstance(finset_intersection, Union):
|
| 347 |
+
elm_in_sets = finset_intersection.args[0]
|
| 348 |
+
return Union(not_empty_in(finset_intersection.args[1], *syms),
|
| 349 |
+
elm_in_sets)
|
| 350 |
+
|
| 351 |
+
if isinstance(finset_intersection, FiniteSet):
|
| 352 |
+
finite_set = finset_intersection
|
| 353 |
+
_sets = S.Reals
|
| 354 |
+
else:
|
| 355 |
+
finite_set = finset_intersection.args[1]
|
| 356 |
+
_sets = finset_intersection.args[0]
|
| 357 |
+
|
| 358 |
+
if not isinstance(finite_set, FiniteSet):
|
| 359 |
+
raise ValueError('A FiniteSet must be given, not %s: %s' %
|
| 360 |
+
(type(finite_set), finite_set))
|
| 361 |
+
|
| 362 |
+
if len(syms) == 1:
|
| 363 |
+
symb = syms[0]
|
| 364 |
+
else:
|
| 365 |
+
raise NotImplementedError('more than one variables %s not handled' %
|
| 366 |
+
(syms,))
|
| 367 |
+
|
| 368 |
+
def elm_domain(expr, intrvl):
|
| 369 |
+
""" Finds the domain of an expression in any given interval """
|
| 370 |
+
from sympy.solvers.solveset import solveset
|
| 371 |
+
|
| 372 |
+
_start = intrvl.start
|
| 373 |
+
_end = intrvl.end
|
| 374 |
+
_singularities = solveset(expr.as_numer_denom()[1], symb,
|
| 375 |
+
domain=S.Reals)
|
| 376 |
+
|
| 377 |
+
if intrvl.right_open:
|
| 378 |
+
if _end is S.Infinity:
|
| 379 |
+
_domain1 = S.Reals
|
| 380 |
+
else:
|
| 381 |
+
_domain1 = solveset(expr < _end, symb, domain=S.Reals)
|
| 382 |
+
else:
|
| 383 |
+
_domain1 = solveset(expr <= _end, symb, domain=S.Reals)
|
| 384 |
+
|
| 385 |
+
if intrvl.left_open:
|
| 386 |
+
if _start is S.NegativeInfinity:
|
| 387 |
+
_domain2 = S.Reals
|
| 388 |
+
else:
|
| 389 |
+
_domain2 = solveset(expr > _start, symb, domain=S.Reals)
|
| 390 |
+
else:
|
| 391 |
+
_domain2 = solveset(expr >= _start, symb, domain=S.Reals)
|
| 392 |
+
|
| 393 |
+
# domain in the interval
|
| 394 |
+
expr_with_sing = Intersection(_domain1, _domain2)
|
| 395 |
+
expr_domain = Complement(expr_with_sing, _singularities)
|
| 396 |
+
return expr_domain
|
| 397 |
+
|
| 398 |
+
if isinstance(_sets, Interval):
|
| 399 |
+
return Union(*[elm_domain(element, _sets) for element in finite_set])
|
| 400 |
+
|
| 401 |
+
if isinstance(_sets, Union):
|
| 402 |
+
_domain = S.EmptySet
|
| 403 |
+
for intrvl in _sets.args:
|
| 404 |
+
_domain_element = Union(*[elm_domain(element, intrvl)
|
| 405 |
+
for element in finite_set])
|
| 406 |
+
_domain = Union(_domain, _domain_element)
|
| 407 |
+
return _domain
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
def periodicity(f, symbol, check=False):
|
| 411 |
+
"""
|
| 412 |
+
Tests the given function for periodicity in the given symbol.
|
| 413 |
+
|
| 414 |
+
Parameters
|
| 415 |
+
==========
|
| 416 |
+
|
| 417 |
+
f : :py:class:`~.Expr`
|
| 418 |
+
The concerned function.
|
| 419 |
+
symbol : :py:class:`~.Symbol`
|
| 420 |
+
The variable for which the period is to be determined.
|
| 421 |
+
check : bool, optional
|
| 422 |
+
The flag to verify whether the value being returned is a period or not.
|
| 423 |
+
|
| 424 |
+
Returns
|
| 425 |
+
=======
|
| 426 |
+
|
| 427 |
+
period
|
| 428 |
+
The period of the function is returned.
|
| 429 |
+
``None`` is returned when the function is aperiodic or has a complex period.
|
| 430 |
+
The value of $0$ is returned as the period of a constant function.
|
| 431 |
+
|
| 432 |
+
Raises
|
| 433 |
+
======
|
| 434 |
+
|
| 435 |
+
NotImplementedError
|
| 436 |
+
The value of the period computed cannot be verified.
|
| 437 |
+
|
| 438 |
+
|
| 439 |
+
Notes
|
| 440 |
+
=====
|
| 441 |
+
|
| 442 |
+
Currently, we do not support functions with a complex period.
|
| 443 |
+
The period of functions having complex periodic values such
|
| 444 |
+
as ``exp``, ``sinh`` is evaluated to ``None``.
|
| 445 |
+
|
| 446 |
+
The value returned might not be the "fundamental" period of the given
|
| 447 |
+
function i.e. it may not be the smallest periodic value of the function.
|
| 448 |
+
|
| 449 |
+
The verification of the period through the ``check`` flag is not reliable
|
| 450 |
+
due to internal simplification of the given expression. Hence, it is set
|
| 451 |
+
to ``False`` by default.
|
| 452 |
+
|
| 453 |
+
Examples
|
| 454 |
+
========
|
| 455 |
+
>>> from sympy import periodicity, Symbol, sin, cos, tan, exp
|
| 456 |
+
>>> x = Symbol('x')
|
| 457 |
+
>>> f = sin(x) + sin(2*x) + sin(3*x)
|
| 458 |
+
>>> periodicity(f, x)
|
| 459 |
+
2*pi
|
| 460 |
+
>>> periodicity(sin(x)*cos(x), x)
|
| 461 |
+
pi
|
| 462 |
+
>>> periodicity(exp(tan(2*x) - 1), x)
|
| 463 |
+
pi/2
|
| 464 |
+
>>> periodicity(sin(4*x)**cos(2*x), x)
|
| 465 |
+
pi
|
| 466 |
+
>>> periodicity(exp(x), x)
|
| 467 |
+
"""
|
| 468 |
+
if symbol.kind is not NumberKind:
|
| 469 |
+
raise NotImplementedError("Cannot use symbol of kind %s" % symbol.kind)
|
| 470 |
+
temp = Dummy('x', real=True)
|
| 471 |
+
f = f.subs(symbol, temp)
|
| 472 |
+
symbol = temp
|
| 473 |
+
|
| 474 |
+
def _check(orig_f, period):
|
| 475 |
+
'''Return the checked period or raise an error.'''
|
| 476 |
+
new_f = orig_f.subs(symbol, symbol + period)
|
| 477 |
+
if new_f.equals(orig_f):
|
| 478 |
+
return period
|
| 479 |
+
else:
|
| 480 |
+
raise NotImplementedError(filldedent('''
|
| 481 |
+
The period of the given function cannot be verified.
|
| 482 |
+
When `%s` was replaced with `%s + %s` in `%s`, the result
|
| 483 |
+
was `%s` which was not recognized as being the same as
|
| 484 |
+
the original function.
|
| 485 |
+
So either the period was wrong or the two forms were
|
| 486 |
+
not recognized as being equal.
|
| 487 |
+
Set check=False to obtain the value.''' %
|
| 488 |
+
(symbol, symbol, period, orig_f, new_f)))
|
| 489 |
+
|
| 490 |
+
orig_f = f
|
| 491 |
+
period = None
|
| 492 |
+
|
| 493 |
+
if isinstance(f, Relational):
|
| 494 |
+
f = f.lhs - f.rhs
|
| 495 |
+
|
| 496 |
+
f = f.simplify()
|
| 497 |
+
|
| 498 |
+
if symbol not in f.free_symbols:
|
| 499 |
+
return S.Zero
|
| 500 |
+
|
| 501 |
+
if isinstance(f, TrigonometricFunction):
|
| 502 |
+
try:
|
| 503 |
+
period = f.period(symbol)
|
| 504 |
+
except NotImplementedError:
|
| 505 |
+
pass
|
| 506 |
+
|
| 507 |
+
if isinstance(f, Abs):
|
| 508 |
+
arg = f.args[0]
|
| 509 |
+
if isinstance(arg, (sec, csc, cos)):
|
| 510 |
+
# all but tan and cot might have a
|
| 511 |
+
# a period that is half as large
|
| 512 |
+
# so recast as sin
|
| 513 |
+
arg = sin(arg.args[0])
|
| 514 |
+
period = periodicity(arg, symbol)
|
| 515 |
+
if period is not None and isinstance(arg, sin):
|
| 516 |
+
# the argument of Abs was a trigonometric other than
|
| 517 |
+
# cot or tan; test to see if the half-period
|
| 518 |
+
# is valid. Abs(arg) has behaviour equivalent to
|
| 519 |
+
# orig_f, so use that for test:
|
| 520 |
+
orig_f = Abs(arg)
|
| 521 |
+
try:
|
| 522 |
+
return _check(orig_f, period/2)
|
| 523 |
+
except NotImplementedError as err:
|
| 524 |
+
if check:
|
| 525 |
+
raise NotImplementedError(err)
|
| 526 |
+
# else let new orig_f and period be
|
| 527 |
+
# checked below
|
| 528 |
+
|
| 529 |
+
if isinstance(f, exp) or (f.is_Pow and f.base == S.Exp1):
|
| 530 |
+
f = Pow(S.Exp1, expand_mul(f.exp))
|
| 531 |
+
if im(f) != 0:
|
| 532 |
+
period_real = periodicity(re(f), symbol)
|
| 533 |
+
period_imag = periodicity(im(f), symbol)
|
| 534 |
+
if period_real is not None and period_imag is not None:
|
| 535 |
+
period = lcim([period_real, period_imag])
|
| 536 |
+
|
| 537 |
+
if f.is_Pow and f.base != S.Exp1:
|
| 538 |
+
base, expo = f.args
|
| 539 |
+
base_has_sym = base.has(symbol)
|
| 540 |
+
expo_has_sym = expo.has(symbol)
|
| 541 |
+
|
| 542 |
+
if base_has_sym and not expo_has_sym:
|
| 543 |
+
period = periodicity(base, symbol)
|
| 544 |
+
|
| 545 |
+
elif expo_has_sym and not base_has_sym:
|
| 546 |
+
period = periodicity(expo, symbol)
|
| 547 |
+
|
| 548 |
+
else:
|
| 549 |
+
period = _periodicity(f.args, symbol)
|
| 550 |
+
|
| 551 |
+
elif f.is_Mul:
|
| 552 |
+
coeff, g = f.as_independent(symbol, as_Add=False)
|
| 553 |
+
if isinstance(g, TrigonometricFunction) or not equal_valued(coeff, 1):
|
| 554 |
+
period = periodicity(g, symbol)
|
| 555 |
+
else:
|
| 556 |
+
period = _periodicity(g.args, symbol)
|
| 557 |
+
|
| 558 |
+
elif f.is_Add:
|
| 559 |
+
k, g = f.as_independent(symbol)
|
| 560 |
+
if k is not S.Zero:
|
| 561 |
+
return periodicity(g, symbol)
|
| 562 |
+
|
| 563 |
+
period = _periodicity(g.args, symbol)
|
| 564 |
+
|
| 565 |
+
elif isinstance(f, Mod):
|
| 566 |
+
a, n = f.args
|
| 567 |
+
|
| 568 |
+
if a == symbol:
|
| 569 |
+
period = n
|
| 570 |
+
elif isinstance(a, TrigonometricFunction):
|
| 571 |
+
period = periodicity(a, symbol)
|
| 572 |
+
#check if 'f' is linear in 'symbol'
|
| 573 |
+
elif (a.is_polynomial(symbol) and degree(a, symbol) == 1 and
|
| 574 |
+
symbol not in n.free_symbols):
|
| 575 |
+
period = Abs(n / a.diff(symbol))
|
| 576 |
+
|
| 577 |
+
elif isinstance(f, Piecewise):
|
| 578 |
+
pass # not handling Piecewise yet as the return type is not favorable
|
| 579 |
+
|
| 580 |
+
elif period is None:
|
| 581 |
+
from sympy.solvers.decompogen import compogen, decompogen
|
| 582 |
+
g_s = decompogen(f, symbol)
|
| 583 |
+
num_of_gs = len(g_s)
|
| 584 |
+
if num_of_gs > 1:
|
| 585 |
+
for index, g in enumerate(reversed(g_s)):
|
| 586 |
+
start_index = num_of_gs - 1 - index
|
| 587 |
+
g = compogen(g_s[start_index:], symbol)
|
| 588 |
+
if g not in (orig_f, f): # Fix for issue 12620
|
| 589 |
+
period = periodicity(g, symbol)
|
| 590 |
+
if period is not None:
|
| 591 |
+
break
|
| 592 |
+
|
| 593 |
+
if period is not None:
|
| 594 |
+
if check:
|
| 595 |
+
return _check(orig_f, period)
|
| 596 |
+
return period
|
| 597 |
+
|
| 598 |
+
return None
|
| 599 |
+
|
| 600 |
+
|
| 601 |
+
def _periodicity(args, symbol):
|
| 602 |
+
"""
|
| 603 |
+
Helper for `periodicity` to find the period of a list of simpler
|
| 604 |
+
functions.
|
| 605 |
+
It uses the `lcim` method to find the least common period of
|
| 606 |
+
all the functions.
|
| 607 |
+
|
| 608 |
+
Parameters
|
| 609 |
+
==========
|
| 610 |
+
|
| 611 |
+
args : Tuple of :py:class:`~.Symbol`
|
| 612 |
+
All the symbols present in a function.
|
| 613 |
+
|
| 614 |
+
symbol : :py:class:`~.Symbol`
|
| 615 |
+
The symbol over which the function is to be evaluated.
|
| 616 |
+
|
| 617 |
+
Returns
|
| 618 |
+
=======
|
| 619 |
+
|
| 620 |
+
period
|
| 621 |
+
The least common period of the function for all the symbols
|
| 622 |
+
of the function.
|
| 623 |
+
``None`` if for at least one of the symbols the function is aperiodic.
|
| 624 |
+
|
| 625 |
+
"""
|
| 626 |
+
periods = []
|
| 627 |
+
for f in args:
|
| 628 |
+
period = periodicity(f, symbol)
|
| 629 |
+
if period is None:
|
| 630 |
+
return None
|
| 631 |
+
|
| 632 |
+
if period is not S.Zero:
|
| 633 |
+
periods.append(period)
|
| 634 |
+
|
| 635 |
+
if len(periods) > 1:
|
| 636 |
+
return lcim(periods)
|
| 637 |
+
|
| 638 |
+
if periods:
|
| 639 |
+
return periods[0]
|
| 640 |
+
|
| 641 |
+
|
| 642 |
+
def lcim(numbers):
|
| 643 |
+
"""Returns the least common integral multiple of a list of numbers.
|
| 644 |
+
|
| 645 |
+
The numbers can be rational or irrational or a mixture of both.
|
| 646 |
+
`None` is returned for incommensurable numbers.
|
| 647 |
+
|
| 648 |
+
Parameters
|
| 649 |
+
==========
|
| 650 |
+
|
| 651 |
+
numbers : list
|
| 652 |
+
Numbers (rational and/or irrational) for which lcim is to be found.
|
| 653 |
+
|
| 654 |
+
Returns
|
| 655 |
+
=======
|
| 656 |
+
|
| 657 |
+
number
|
| 658 |
+
lcim if it exists, otherwise ``None`` for incommensurable numbers.
|
| 659 |
+
|
| 660 |
+
Examples
|
| 661 |
+
========
|
| 662 |
+
|
| 663 |
+
>>> from sympy.calculus.util import lcim
|
| 664 |
+
>>> from sympy import S, pi
|
| 665 |
+
>>> lcim([S(1)/2, S(3)/4, S(5)/6])
|
| 666 |
+
15/2
|
| 667 |
+
>>> lcim([2*pi, 3*pi, pi, pi/2])
|
| 668 |
+
6*pi
|
| 669 |
+
>>> lcim([S(1), 2*pi])
|
| 670 |
+
"""
|
| 671 |
+
result = None
|
| 672 |
+
if all(num.is_irrational for num in numbers):
|
| 673 |
+
factorized_nums = [num.factor() for num in numbers]
|
| 674 |
+
factors_num = [num.as_coeff_Mul() for num in factorized_nums]
|
| 675 |
+
term = factors_num[0][1]
|
| 676 |
+
if all(factor == term for coeff, factor in factors_num):
|
| 677 |
+
common_term = term
|
| 678 |
+
coeffs = [coeff for coeff, factor in factors_num]
|
| 679 |
+
result = lcm_list(coeffs) * common_term
|
| 680 |
+
|
| 681 |
+
elif all(num.is_rational for num in numbers):
|
| 682 |
+
result = lcm_list(numbers)
|
| 683 |
+
|
| 684 |
+
else:
|
| 685 |
+
pass
|
| 686 |
+
|
| 687 |
+
return result
|
| 688 |
+
|
| 689 |
+
def is_convex(f, *syms, domain=S.Reals):
|
| 690 |
+
r"""Determines the convexity of the function passed in the argument.
|
| 691 |
+
|
| 692 |
+
Parameters
|
| 693 |
+
==========
|
| 694 |
+
|
| 695 |
+
f : :py:class:`~.Expr`
|
| 696 |
+
The concerned function.
|
| 697 |
+
syms : Tuple of :py:class:`~.Symbol`
|
| 698 |
+
The variables with respect to which the convexity is to be determined.
|
| 699 |
+
domain : :py:class:`~.Interval`, optional
|
| 700 |
+
The domain over which the convexity of the function has to be checked.
|
| 701 |
+
If unspecified, S.Reals will be the default domain.
|
| 702 |
+
|
| 703 |
+
Returns
|
| 704 |
+
=======
|
| 705 |
+
|
| 706 |
+
bool
|
| 707 |
+
The method returns ``True`` if the function is convex otherwise it
|
| 708 |
+
returns ``False``.
|
| 709 |
+
|
| 710 |
+
Raises
|
| 711 |
+
======
|
| 712 |
+
|
| 713 |
+
NotImplementedError
|
| 714 |
+
The check for the convexity of multivariate functions is not implemented yet.
|
| 715 |
+
|
| 716 |
+
Notes
|
| 717 |
+
=====
|
| 718 |
+
|
| 719 |
+
To determine concavity of a function pass `-f` as the concerned function.
|
| 720 |
+
To determine logarithmic convexity of a function pass `\log(f)` as
|
| 721 |
+
concerned function.
|
| 722 |
+
To determine logarithmic concavity of a function pass `-\log(f)` as
|
| 723 |
+
concerned function.
|
| 724 |
+
|
| 725 |
+
Currently, convexity check of multivariate functions is not handled.
|
| 726 |
+
|
| 727 |
+
Examples
|
| 728 |
+
========
|
| 729 |
+
|
| 730 |
+
>>> from sympy import is_convex, symbols, exp, oo, Interval
|
| 731 |
+
>>> x = symbols('x')
|
| 732 |
+
>>> is_convex(exp(x), x)
|
| 733 |
+
True
|
| 734 |
+
>>> is_convex(x**3, x, domain = Interval(-1, oo))
|
| 735 |
+
False
|
| 736 |
+
>>> is_convex(1/x**2, x, domain=Interval.open(0, oo))
|
| 737 |
+
True
|
| 738 |
+
|
| 739 |
+
References
|
| 740 |
+
==========
|
| 741 |
+
|
| 742 |
+
.. [1] https://en.wikipedia.org/wiki/Convex_function
|
| 743 |
+
.. [2] http://www.ifp.illinois.edu/~angelia/L3_convfunc.pdf
|
| 744 |
+
.. [3] https://en.wikipedia.org/wiki/Logarithmically_convex_function
|
| 745 |
+
.. [4] https://en.wikipedia.org/wiki/Logarithmically_concave_function
|
| 746 |
+
.. [5] https://en.wikipedia.org/wiki/Concave_function
|
| 747 |
+
|
| 748 |
+
"""
|
| 749 |
+
if len(syms) > 1 :
|
| 750 |
+
return hessian(f, syms).is_positive_semidefinite
|
| 751 |
+
from sympy.solvers.inequalities import solve_univariate_inequality
|
| 752 |
+
f = _sympify(f)
|
| 753 |
+
var = syms[0]
|
| 754 |
+
if any(s in domain for s in singularities(f, var)):
|
| 755 |
+
return False
|
| 756 |
+
condition = f.diff(var, 2) < 0
|
| 757 |
+
if solve_univariate_inequality(condition, var, False, domain):
|
| 758 |
+
return False
|
| 759 |
+
return True
|
| 760 |
+
|
| 761 |
+
|
| 762 |
+
def stationary_points(f, symbol, domain=S.Reals):
|
| 763 |
+
"""
|
| 764 |
+
Returns the stationary points of a function (where derivative of the
|
| 765 |
+
function is 0) in the given domain.
|
| 766 |
+
|
| 767 |
+
Parameters
|
| 768 |
+
==========
|
| 769 |
+
|
| 770 |
+
f : :py:class:`~.Expr`
|
| 771 |
+
The concerned function.
|
| 772 |
+
symbol : :py:class:`~.Symbol`
|
| 773 |
+
The variable for which the stationary points are to be determined.
|
| 774 |
+
domain : :py:class:`~.Interval`
|
| 775 |
+
The domain over which the stationary points have to be checked.
|
| 776 |
+
If unspecified, ``S.Reals`` will be the default domain.
|
| 777 |
+
|
| 778 |
+
Returns
|
| 779 |
+
=======
|
| 780 |
+
|
| 781 |
+
Set
|
| 782 |
+
A set of stationary points for the function. If there are no
|
| 783 |
+
stationary point, an :py:class:`~.EmptySet` is returned.
|
| 784 |
+
|
| 785 |
+
Examples
|
| 786 |
+
========
|
| 787 |
+
|
| 788 |
+
>>> from sympy import Interval, Symbol, S, sin, pi, pprint, stationary_points
|
| 789 |
+
>>> x = Symbol('x')
|
| 790 |
+
|
| 791 |
+
>>> stationary_points(1/x, x, S.Reals)
|
| 792 |
+
EmptySet
|
| 793 |
+
|
| 794 |
+
>>> pprint(stationary_points(sin(x), x), use_unicode=False)
|
| 795 |
+
pi 3*pi
|
| 796 |
+
{2*n*pi + -- | n in Integers} U {2*n*pi + ---- | n in Integers}
|
| 797 |
+
2 2
|
| 798 |
+
|
| 799 |
+
>>> stationary_points(sin(x),x, Interval(0, 4*pi))
|
| 800 |
+
{pi/2, 3*pi/2, 5*pi/2, 7*pi/2}
|
| 801 |
+
|
| 802 |
+
"""
|
| 803 |
+
from sympy.solvers.solveset import solveset
|
| 804 |
+
|
| 805 |
+
if domain is S.EmptySet:
|
| 806 |
+
return S.EmptySet
|
| 807 |
+
|
| 808 |
+
domain = continuous_domain(f, symbol, domain)
|
| 809 |
+
set = solveset(diff(f, symbol), symbol, domain)
|
| 810 |
+
|
| 811 |
+
return set
|
| 812 |
+
|
| 813 |
+
|
| 814 |
+
def maximum(f, symbol, domain=S.Reals):
|
| 815 |
+
"""
|
| 816 |
+
Returns the maximum value of a function in the given domain.
|
| 817 |
+
|
| 818 |
+
Parameters
|
| 819 |
+
==========
|
| 820 |
+
|
| 821 |
+
f : :py:class:`~.Expr`
|
| 822 |
+
The concerned function.
|
| 823 |
+
symbol : :py:class:`~.Symbol`
|
| 824 |
+
The variable for maximum value needs to be determined.
|
| 825 |
+
domain : :py:class:`~.Interval`
|
| 826 |
+
The domain over which the maximum have to be checked.
|
| 827 |
+
If unspecified, then the global maximum is returned.
|
| 828 |
+
|
| 829 |
+
Returns
|
| 830 |
+
=======
|
| 831 |
+
|
| 832 |
+
number
|
| 833 |
+
Maximum value of the function in given domain.
|
| 834 |
+
|
| 835 |
+
Examples
|
| 836 |
+
========
|
| 837 |
+
|
| 838 |
+
>>> from sympy import Interval, Symbol, S, sin, cos, pi, maximum
|
| 839 |
+
>>> x = Symbol('x')
|
| 840 |
+
|
| 841 |
+
>>> f = -x**2 + 2*x + 5
|
| 842 |
+
>>> maximum(f, x, S.Reals)
|
| 843 |
+
6
|
| 844 |
+
|
| 845 |
+
>>> maximum(sin(x), x, Interval(-pi, pi/4))
|
| 846 |
+
sqrt(2)/2
|
| 847 |
+
|
| 848 |
+
>>> maximum(sin(x)*cos(x), x)
|
| 849 |
+
1/2
|
| 850 |
+
|
| 851 |
+
"""
|
| 852 |
+
if isinstance(symbol, Symbol):
|
| 853 |
+
if domain is S.EmptySet:
|
| 854 |
+
raise ValueError("Maximum value not defined for empty domain.")
|
| 855 |
+
|
| 856 |
+
return function_range(f, symbol, domain).sup
|
| 857 |
+
else:
|
| 858 |
+
raise ValueError("%s is not a valid symbol." % symbol)
|
| 859 |
+
|
| 860 |
+
|
| 861 |
+
def minimum(f, symbol, domain=S.Reals):
|
| 862 |
+
"""
|
| 863 |
+
Returns the minimum value of a function in the given domain.
|
| 864 |
+
|
| 865 |
+
Parameters
|
| 866 |
+
==========
|
| 867 |
+
|
| 868 |
+
f : :py:class:`~.Expr`
|
| 869 |
+
The concerned function.
|
| 870 |
+
symbol : :py:class:`~.Symbol`
|
| 871 |
+
The variable for minimum value needs to be determined.
|
| 872 |
+
domain : :py:class:`~.Interval`
|
| 873 |
+
The domain over which the minimum have to be checked.
|
| 874 |
+
If unspecified, then the global minimum is returned.
|
| 875 |
+
|
| 876 |
+
Returns
|
| 877 |
+
=======
|
| 878 |
+
|
| 879 |
+
number
|
| 880 |
+
Minimum value of the function in the given domain.
|
| 881 |
+
|
| 882 |
+
Examples
|
| 883 |
+
========
|
| 884 |
+
|
| 885 |
+
>>> from sympy import Interval, Symbol, S, sin, cos, minimum
|
| 886 |
+
>>> x = Symbol('x')
|
| 887 |
+
|
| 888 |
+
>>> f = x**2 + 2*x + 5
|
| 889 |
+
>>> minimum(f, x, S.Reals)
|
| 890 |
+
4
|
| 891 |
+
|
| 892 |
+
>>> minimum(sin(x), x, Interval(2, 3))
|
| 893 |
+
sin(3)
|
| 894 |
+
|
| 895 |
+
>>> minimum(sin(x)*cos(x), x)
|
| 896 |
+
-1/2
|
| 897 |
+
|
| 898 |
+
"""
|
| 899 |
+
if isinstance(symbol, Symbol):
|
| 900 |
+
if domain is S.EmptySet:
|
| 901 |
+
raise ValueError("Minimum value not defined for empty domain.")
|
| 902 |
+
|
| 903 |
+
return function_range(f, symbol, domain).inf
|
| 904 |
+
else:
|
| 905 |
+
raise ValueError("%s is not a valid symbol." % symbol)
|
infer_4_47_1/lib/python3.10/site-packages/sympy/core/__pycache__/expr.cpython-310.pyc
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:ec71bbf3d58b1228b3a83216cbe6eb37c374bec898652cbf77684ad61ffd268c
|
| 3 |
+
size 114999
|
infer_4_47_1/lib/python3.10/site-packages/sympy/core/__pycache__/function.cpython-310.pyc
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:4463d8571e37714d6da59f6813de78ac2f03f6c4b584451fd65e4685b266d63f
|
| 3 |
+
size 101044
|
infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/__init__.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Number theory module (primes, etc)
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from .generate import nextprime, prevprime, prime, primepi, primerange, \
|
| 6 |
+
randprime, Sieve, sieve, primorial, cycle_length, composite, compositepi
|
| 7 |
+
from .primetest import isprime, is_gaussian_prime, is_mersenne_prime
|
| 8 |
+
from .factor_ import divisors, proper_divisors, factorint, multiplicity, \
|
| 9 |
+
multiplicity_in_factorial, perfect_power, pollard_pm1, pollard_rho, \
|
| 10 |
+
primefactors, totient, \
|
| 11 |
+
divisor_count, proper_divisor_count, divisor_sigma, factorrat, \
|
| 12 |
+
reduced_totient, primenu, primeomega, mersenne_prime_exponent, \
|
| 13 |
+
is_perfect, is_abundant, is_deficient, is_amicable, is_carmichael, \
|
| 14 |
+
abundance, dra, drm
|
| 15 |
+
|
| 16 |
+
from .partitions_ import npartitions
|
| 17 |
+
from .residue_ntheory import is_primitive_root, is_quad_residue, \
|
| 18 |
+
legendre_symbol, jacobi_symbol, n_order, sqrt_mod, quadratic_residues, \
|
| 19 |
+
primitive_root, nthroot_mod, is_nthpow_residue, sqrt_mod_iter, mobius, \
|
| 20 |
+
discrete_log, quadratic_congruence, polynomial_congruence
|
| 21 |
+
from .multinomial import binomial_coefficients, binomial_coefficients_list, \
|
| 22 |
+
multinomial_coefficients
|
| 23 |
+
from .continued_fraction import continued_fraction_periodic, \
|
| 24 |
+
continued_fraction_iterator, continued_fraction_reduce, \
|
| 25 |
+
continued_fraction_convergents, continued_fraction
|
| 26 |
+
from .digits import count_digits, digits, is_palindromic
|
| 27 |
+
from .egyptian_fraction import egyptian_fraction
|
| 28 |
+
from .ecm import ecm
|
| 29 |
+
from .qs import qs
|
| 30 |
+
__all__ = [
|
| 31 |
+
'nextprime', 'prevprime', 'prime', 'primepi', 'primerange', 'randprime',
|
| 32 |
+
'Sieve', 'sieve', 'primorial', 'cycle_length', 'composite', 'compositepi',
|
| 33 |
+
|
| 34 |
+
'isprime', 'is_gaussian_prime', 'is_mersenne_prime',
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
'divisors', 'proper_divisors', 'factorint', 'multiplicity', 'perfect_power',
|
| 38 |
+
'pollard_pm1', 'pollard_rho', 'primefactors', 'totient',
|
| 39 |
+
'divisor_count', 'proper_divisor_count', 'divisor_sigma', 'factorrat',
|
| 40 |
+
'reduced_totient', 'primenu', 'primeomega', 'mersenne_prime_exponent',
|
| 41 |
+
'is_perfect', 'is_abundant', 'is_deficient', 'is_amicable',
|
| 42 |
+
'is_carmichael', 'abundance', 'dra', 'drm', 'multiplicity_in_factorial',
|
| 43 |
+
|
| 44 |
+
'npartitions',
|
| 45 |
+
|
| 46 |
+
'is_primitive_root', 'is_quad_residue', 'legendre_symbol',
|
| 47 |
+
'jacobi_symbol', 'n_order', 'sqrt_mod', 'quadratic_residues',
|
| 48 |
+
'primitive_root', 'nthroot_mod', 'is_nthpow_residue', 'sqrt_mod_iter',
|
| 49 |
+
'mobius', 'discrete_log', 'quadratic_congruence', 'polynomial_congruence',
|
| 50 |
+
|
| 51 |
+
'binomial_coefficients', 'binomial_coefficients_list',
|
| 52 |
+
'multinomial_coefficients',
|
| 53 |
+
|
| 54 |
+
'continued_fraction_periodic', 'continued_fraction_iterator',
|
| 55 |
+
'continued_fraction_reduce', 'continued_fraction_convergents',
|
| 56 |
+
'continued_fraction',
|
| 57 |
+
|
| 58 |
+
'digits',
|
| 59 |
+
'count_digits',
|
| 60 |
+
'is_palindromic',
|
| 61 |
+
|
| 62 |
+
'egyptian_fraction',
|
| 63 |
+
|
| 64 |
+
'ecm',
|
| 65 |
+
|
| 66 |
+
'qs',
|
| 67 |
+
]
|
infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (2.5 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/__pycache__/digits.cpython-310.pyc
ADDED
|
Binary file (4.02 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/__pycache__/elliptic_curve.cpython-310.pyc
ADDED
|
Binary file (12 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/__pycache__/generate.cpython-310.pyc
ADDED
|
Binary file (30.5 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/__pycache__/primetest.cpython-310.pyc
ADDED
|
Binary file (18.8 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/__pycache__/qs.cpython-310.pyc
ADDED
|
Binary file (15.5 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/bbp_pi.py
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
'''
|
| 2 |
+
This implementation is a heavily modified fixed point implementation of
|
| 3 |
+
BBP_formula for calculating the nth position of pi. The original hosted
|
| 4 |
+
at: https://web.archive.org/web/20151116045029/http://en.literateprograms.org/Pi_with_the_BBP_formula_(Python)
|
| 5 |
+
|
| 6 |
+
# Permission is hereby granted, free of charge, to any person obtaining
|
| 7 |
+
# a copy of this software and associated documentation files (the
|
| 8 |
+
# "Software"), to deal in the Software without restriction, including
|
| 9 |
+
# without limitation the rights to use, copy, modify, merge, publish,
|
| 10 |
+
# distribute, sub-license, and/or sell copies of the Software, and to
|
| 11 |
+
# permit persons to whom the Software is furnished to do so, subject to
|
| 12 |
+
# the following conditions:
|
| 13 |
+
#
|
| 14 |
+
# The above copyright notice and this permission notice shall be
|
| 15 |
+
# included in all copies or substantial portions of the Software.
|
| 16 |
+
#
|
| 17 |
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
| 18 |
+
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
| 19 |
+
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
| 20 |
+
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
| 21 |
+
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
|
| 22 |
+
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
|
| 23 |
+
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
| 24 |
+
|
| 25 |
+
Modifications:
|
| 26 |
+
|
| 27 |
+
1.Once the nth digit and desired number of digits is selected, the
|
| 28 |
+
number of digits of working precision is calculated to ensure that
|
| 29 |
+
the hexadecimal digits returned are accurate. This is calculated as
|
| 30 |
+
|
| 31 |
+
int(math.log(start + prec)/math.log(16) + prec + 3)
|
| 32 |
+
--------------------------------------- --------
|
| 33 |
+
/ /
|
| 34 |
+
number of hex digits additional digits
|
| 35 |
+
|
| 36 |
+
This was checked by the following code which completed without
|
| 37 |
+
errors (and dig are the digits included in the test_bbp.py file):
|
| 38 |
+
|
| 39 |
+
for i in range(0,1000):
|
| 40 |
+
for j in range(1,1000):
|
| 41 |
+
a, b = pi_hex_digits(i, j), dig[i:i+j]
|
| 42 |
+
if a != b:
|
| 43 |
+
print('%s\n%s'%(a,b))
|
| 44 |
+
|
| 45 |
+
Deceasing the additional digits by 1 generated errors, so '3' is
|
| 46 |
+
the smallest additional precision needed to calculate the above
|
| 47 |
+
loop without errors. The following trailing 10 digits were also
|
| 48 |
+
checked to be accurate (and the times were slightly faster with
|
| 49 |
+
some of the constant modifications that were made):
|
| 50 |
+
|
| 51 |
+
>> from time import time
|
| 52 |
+
>> t=time();pi_hex_digits(10**2-10 + 1, 10), time()-t
|
| 53 |
+
('e90c6cc0ac', 0.0)
|
| 54 |
+
>> t=time();pi_hex_digits(10**4-10 + 1, 10), time()-t
|
| 55 |
+
('26aab49ec6', 0.17100000381469727)
|
| 56 |
+
>> t=time();pi_hex_digits(10**5-10 + 1, 10), time()-t
|
| 57 |
+
('a22673c1a5', 4.7109999656677246)
|
| 58 |
+
>> t=time();pi_hex_digits(10**6-10 + 1, 10), time()-t
|
| 59 |
+
('9ffd342362', 59.985999822616577)
|
| 60 |
+
>> t=time();pi_hex_digits(10**7-10 + 1, 10), time()-t
|
| 61 |
+
('c1a42e06a1', 689.51800012588501)
|
| 62 |
+
|
| 63 |
+
2. The while loop to evaluate whether the series has converged quits
|
| 64 |
+
when the addition amount `dt` has dropped to zero.
|
| 65 |
+
|
| 66 |
+
3. the formatting string to convert the decimal to hexadecimal is
|
| 67 |
+
calculated for the given precision.
|
| 68 |
+
|
| 69 |
+
4. pi_hex_digits(n) changed to have coefficient to the formula in an
|
| 70 |
+
array (perhaps just a matter of preference).
|
| 71 |
+
|
| 72 |
+
'''
|
| 73 |
+
|
| 74 |
+
from sympy.utilities.misc import as_int
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def _series(j, n, prec=14):
|
| 78 |
+
|
| 79 |
+
# Left sum from the bbp algorithm
|
| 80 |
+
s = 0
|
| 81 |
+
D = _dn(n, prec)
|
| 82 |
+
D4 = 4 * D
|
| 83 |
+
d = j
|
| 84 |
+
for k in range(n + 1):
|
| 85 |
+
s += (pow(16, n - k, d) << D4) // d
|
| 86 |
+
d += 8
|
| 87 |
+
|
| 88 |
+
# Right sum iterates to infinity for full precision, but we
|
| 89 |
+
# stop at the point where one iteration is beyond the precision
|
| 90 |
+
# specified.
|
| 91 |
+
|
| 92 |
+
t = 0
|
| 93 |
+
k = n + 1
|
| 94 |
+
e = D4 - 4 # 4*(D + n - k)
|
| 95 |
+
d = 8 * k + j
|
| 96 |
+
while True:
|
| 97 |
+
dt = (1 << e) // d
|
| 98 |
+
if not dt:
|
| 99 |
+
break
|
| 100 |
+
t += dt
|
| 101 |
+
# k += 1
|
| 102 |
+
e -= 4
|
| 103 |
+
d += 8
|
| 104 |
+
total = s + t
|
| 105 |
+
|
| 106 |
+
return total
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def pi_hex_digits(n, prec=14):
|
| 110 |
+
"""Returns a string containing ``prec`` (default 14) digits
|
| 111 |
+
starting at the nth digit of pi in hex. Counting of digits
|
| 112 |
+
starts at 0 and the decimal is not counted, so for n = 0 the
|
| 113 |
+
returned value starts with 3; n = 1 corresponds to the first
|
| 114 |
+
digit past the decimal point (which in hex is 2).
|
| 115 |
+
|
| 116 |
+
Parameters
|
| 117 |
+
==========
|
| 118 |
+
|
| 119 |
+
n : non-negative integer
|
| 120 |
+
prec : non-negative integer. default = 14
|
| 121 |
+
|
| 122 |
+
Returns
|
| 123 |
+
=======
|
| 124 |
+
|
| 125 |
+
str : Returns a string containing ``prec`` digits
|
| 126 |
+
starting at the nth digit of pi in hex.
|
| 127 |
+
If ``prec`` = 0, returns empty string.
|
| 128 |
+
|
| 129 |
+
Raises
|
| 130 |
+
======
|
| 131 |
+
|
| 132 |
+
ValueError
|
| 133 |
+
If ``n`` < 0 or ``prec`` < 0.
|
| 134 |
+
Or ``n`` or ``prec`` is not an integer.
|
| 135 |
+
|
| 136 |
+
Examples
|
| 137 |
+
========
|
| 138 |
+
|
| 139 |
+
>>> from sympy.ntheory.bbp_pi import pi_hex_digits
|
| 140 |
+
>>> pi_hex_digits(0)
|
| 141 |
+
'3243f6a8885a30'
|
| 142 |
+
>>> pi_hex_digits(0, 3)
|
| 143 |
+
'324'
|
| 144 |
+
|
| 145 |
+
These are consistent with the following results
|
| 146 |
+
|
| 147 |
+
>>> import math
|
| 148 |
+
>>> hex(int(math.pi * 2**((14-1)*4)))
|
| 149 |
+
'0x3243f6a8885a30'
|
| 150 |
+
>>> hex(int(math.pi * 2**((3-1)*4)))
|
| 151 |
+
'0x324'
|
| 152 |
+
|
| 153 |
+
References
|
| 154 |
+
==========
|
| 155 |
+
|
| 156 |
+
.. [1] http://www.numberworld.org/digits/Pi/
|
| 157 |
+
"""
|
| 158 |
+
n, prec = as_int(n), as_int(prec)
|
| 159 |
+
if n < 0:
|
| 160 |
+
raise ValueError('n cannot be negative')
|
| 161 |
+
if prec < 0:
|
| 162 |
+
raise ValueError('prec cannot be negative')
|
| 163 |
+
if prec == 0:
|
| 164 |
+
return ''
|
| 165 |
+
|
| 166 |
+
# main of implementation arrays holding formulae coefficients
|
| 167 |
+
n -= 1
|
| 168 |
+
a = [4, 2, 1, 1]
|
| 169 |
+
j = [1, 4, 5, 6]
|
| 170 |
+
|
| 171 |
+
#formulae
|
| 172 |
+
D = _dn(n, prec)
|
| 173 |
+
x = + (a[0]*_series(j[0], n, prec)
|
| 174 |
+
- a[1]*_series(j[1], n, prec)
|
| 175 |
+
- a[2]*_series(j[2], n, prec)
|
| 176 |
+
- a[3]*_series(j[3], n, prec)) & (16**D - 1)
|
| 177 |
+
|
| 178 |
+
s = ("%0" + "%ix" % prec) % (x // 16**(D - prec))
|
| 179 |
+
return s
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def _dn(n, prec):
|
| 183 |
+
# controller for n dependence on precision
|
| 184 |
+
# n = starting digit index
|
| 185 |
+
# prec = the number of total digits to compute
|
| 186 |
+
n += 1 # because we subtract 1 for _series
|
| 187 |
+
|
| 188 |
+
# assert int(math.log(n + prec)/math.log(16)) ==\
|
| 189 |
+
# ((n + prec).bit_length() - 1) // 4
|
| 190 |
+
return ((n + prec).bit_length() - 1) // 4 + prec + 3
|
infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/continued_fraction.py
ADDED
|
@@ -0,0 +1,369 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
import itertools
|
| 3 |
+
from sympy.core.exprtools import factor_terms
|
| 4 |
+
from sympy.core.numbers import Integer, Rational
|
| 5 |
+
from sympy.core.singleton import S
|
| 6 |
+
from sympy.core.symbol import Dummy
|
| 7 |
+
from sympy.core.sympify import _sympify
|
| 8 |
+
from sympy.utilities.misc import as_int
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def continued_fraction(a) -> list:
|
| 12 |
+
"""Return the continued fraction representation of a Rational or
|
| 13 |
+
quadratic irrational.
|
| 14 |
+
|
| 15 |
+
Examples
|
| 16 |
+
========
|
| 17 |
+
|
| 18 |
+
>>> from sympy.ntheory.continued_fraction import continued_fraction
|
| 19 |
+
>>> from sympy import sqrt
|
| 20 |
+
>>> continued_fraction((1 + 2*sqrt(3))/5)
|
| 21 |
+
[0, 1, [8, 3, 34, 3]]
|
| 22 |
+
|
| 23 |
+
See Also
|
| 24 |
+
========
|
| 25 |
+
continued_fraction_periodic, continued_fraction_reduce, continued_fraction_convergents
|
| 26 |
+
"""
|
| 27 |
+
e = _sympify(a)
|
| 28 |
+
if all(i.is_Rational for i in e.atoms()):
|
| 29 |
+
if e.is_Integer:
|
| 30 |
+
return continued_fraction_periodic(e, 1, 0)
|
| 31 |
+
elif e.is_Rational:
|
| 32 |
+
return continued_fraction_periodic(e.p, e.q, 0)
|
| 33 |
+
elif e.is_Pow and e.exp is S.Half and e.base.is_Integer:
|
| 34 |
+
return continued_fraction_periodic(0, 1, e.base)
|
| 35 |
+
elif e.is_Mul and len(e.args) == 2 and (
|
| 36 |
+
e.args[0].is_Rational and
|
| 37 |
+
e.args[1].is_Pow and
|
| 38 |
+
e.args[1].base.is_Integer and
|
| 39 |
+
e.args[1].exp is S.Half):
|
| 40 |
+
a, b = e.args
|
| 41 |
+
return continued_fraction_periodic(0, a.q, b.base, a.p)
|
| 42 |
+
else:
|
| 43 |
+
# this should not have to work very hard- no
|
| 44 |
+
# simplification, cancel, etc... which should be
|
| 45 |
+
# done by the user. e.g. This is a fancy 1 but
|
| 46 |
+
# the user should simplify it first:
|
| 47 |
+
# sqrt(2)*(1 + sqrt(2))/(sqrt(2) + 2)
|
| 48 |
+
p, d = e.expand().as_numer_denom()
|
| 49 |
+
if d.is_Integer:
|
| 50 |
+
if p.is_Rational:
|
| 51 |
+
return continued_fraction_periodic(p, d)
|
| 52 |
+
# look for a + b*c
|
| 53 |
+
# with c = sqrt(s)
|
| 54 |
+
if p.is_Add and len(p.args) == 2:
|
| 55 |
+
a, bc = p.args
|
| 56 |
+
else:
|
| 57 |
+
a = S.Zero
|
| 58 |
+
bc = p
|
| 59 |
+
if a.is_Integer:
|
| 60 |
+
b = S.NaN
|
| 61 |
+
if bc.is_Mul and len(bc.args) == 2:
|
| 62 |
+
b, c = bc.args
|
| 63 |
+
elif bc.is_Pow:
|
| 64 |
+
b = Integer(1)
|
| 65 |
+
c = bc
|
| 66 |
+
if b.is_Integer and (
|
| 67 |
+
c.is_Pow and c.exp is S.Half and
|
| 68 |
+
c.base.is_Integer):
|
| 69 |
+
# (a + b*sqrt(c))/d
|
| 70 |
+
c = c.base
|
| 71 |
+
return continued_fraction_periodic(a, d, c, b)
|
| 72 |
+
raise ValueError(
|
| 73 |
+
'expecting a rational or quadratic irrational, not %s' % e)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def continued_fraction_periodic(p, q, d=0, s=1) -> list:
|
| 77 |
+
r"""
|
| 78 |
+
Find the periodic continued fraction expansion of a quadratic irrational.
|
| 79 |
+
|
| 80 |
+
Compute the continued fraction expansion of a rational or a
|
| 81 |
+
quadratic irrational number, i.e. `\frac{p + s\sqrt{d}}{q}`, where
|
| 82 |
+
`p`, `q \ne 0` and `d \ge 0` are integers.
|
| 83 |
+
|
| 84 |
+
Returns the continued fraction representation (canonical form) as
|
| 85 |
+
a list of integers, optionally ending (for quadratic irrationals)
|
| 86 |
+
with list of integers representing the repeating digits.
|
| 87 |
+
|
| 88 |
+
Parameters
|
| 89 |
+
==========
|
| 90 |
+
|
| 91 |
+
p : int
|
| 92 |
+
the rational part of the number's numerator
|
| 93 |
+
q : int
|
| 94 |
+
the denominator of the number
|
| 95 |
+
d : int, optional
|
| 96 |
+
the irrational part (discriminator) of the number's numerator
|
| 97 |
+
s : int, optional
|
| 98 |
+
the coefficient of the irrational part
|
| 99 |
+
|
| 100 |
+
Examples
|
| 101 |
+
========
|
| 102 |
+
|
| 103 |
+
>>> from sympy.ntheory.continued_fraction import continued_fraction_periodic
|
| 104 |
+
>>> continued_fraction_periodic(3, 2, 7)
|
| 105 |
+
[2, [1, 4, 1, 1]]
|
| 106 |
+
|
| 107 |
+
Golden ratio has the simplest continued fraction expansion:
|
| 108 |
+
|
| 109 |
+
>>> continued_fraction_periodic(1, 2, 5)
|
| 110 |
+
[[1]]
|
| 111 |
+
|
| 112 |
+
If the discriminator is zero or a perfect square then the number will be a
|
| 113 |
+
rational number:
|
| 114 |
+
|
| 115 |
+
>>> continued_fraction_periodic(4, 3, 0)
|
| 116 |
+
[1, 3]
|
| 117 |
+
>>> continued_fraction_periodic(4, 3, 49)
|
| 118 |
+
[3, 1, 2]
|
| 119 |
+
|
| 120 |
+
See Also
|
| 121 |
+
========
|
| 122 |
+
|
| 123 |
+
continued_fraction_iterator, continued_fraction_reduce
|
| 124 |
+
|
| 125 |
+
References
|
| 126 |
+
==========
|
| 127 |
+
|
| 128 |
+
.. [1] https://en.wikipedia.org/wiki/Periodic_continued_fraction
|
| 129 |
+
.. [2] K. Rosen. Elementary Number theory and its applications.
|
| 130 |
+
Addison-Wesley, 3 Sub edition, pages 379-381, January 1992.
|
| 131 |
+
|
| 132 |
+
"""
|
| 133 |
+
from sympy.functions import sqrt, floor
|
| 134 |
+
|
| 135 |
+
p, q, d, s = list(map(as_int, [p, q, d, s]))
|
| 136 |
+
|
| 137 |
+
if d < 0:
|
| 138 |
+
raise ValueError("expected non-negative for `d` but got %s" % d)
|
| 139 |
+
|
| 140 |
+
if q == 0:
|
| 141 |
+
raise ValueError("The denominator cannot be 0.")
|
| 142 |
+
|
| 143 |
+
if not s:
|
| 144 |
+
d = 0
|
| 145 |
+
|
| 146 |
+
# check for rational case
|
| 147 |
+
sd = sqrt(d)
|
| 148 |
+
if sd.is_Integer:
|
| 149 |
+
return list(continued_fraction_iterator(Rational(p + s*sd, q)))
|
| 150 |
+
|
| 151 |
+
# irrational case with sd != Integer
|
| 152 |
+
if q < 0:
|
| 153 |
+
p, q, s = -p, -q, -s
|
| 154 |
+
|
| 155 |
+
n = (p + s*sd)/q
|
| 156 |
+
if n < 0:
|
| 157 |
+
w = floor(-n)
|
| 158 |
+
f = -n - w
|
| 159 |
+
one_f = continued_fraction(1 - f) # 1-f < 1 so cf is [0 ... [...]]
|
| 160 |
+
one_f[0] -= w + 1
|
| 161 |
+
return one_f
|
| 162 |
+
|
| 163 |
+
d *= s**2
|
| 164 |
+
sd *= s
|
| 165 |
+
|
| 166 |
+
if (d - p**2)%q:
|
| 167 |
+
d *= q**2
|
| 168 |
+
sd *= q
|
| 169 |
+
p *= q
|
| 170 |
+
q *= q
|
| 171 |
+
|
| 172 |
+
terms: list[int] = []
|
| 173 |
+
pq = {}
|
| 174 |
+
|
| 175 |
+
while (p, q) not in pq:
|
| 176 |
+
pq[(p, q)] = len(terms)
|
| 177 |
+
terms.append((p + sd)//q)
|
| 178 |
+
p = terms[-1]*q - p
|
| 179 |
+
q = (d - p**2)//q
|
| 180 |
+
|
| 181 |
+
i = pq[(p, q)]
|
| 182 |
+
return terms[:i] + [terms[i:]] # type: ignore
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def continued_fraction_reduce(cf):
|
| 186 |
+
"""
|
| 187 |
+
Reduce a continued fraction to a rational or quadratic irrational.
|
| 188 |
+
|
| 189 |
+
Compute the rational or quadratic irrational number from its
|
| 190 |
+
terminating or periodic continued fraction expansion. The
|
| 191 |
+
continued fraction expansion (cf) should be supplied as a
|
| 192 |
+
terminating iterator supplying the terms of the expansion. For
|
| 193 |
+
terminating continued fractions, this is equivalent to
|
| 194 |
+
``list(continued_fraction_convergents(cf))[-1]``, only a little more
|
| 195 |
+
efficient. If the expansion has a repeating part, a list of the
|
| 196 |
+
repeating terms should be returned as the last element from the
|
| 197 |
+
iterator. This is the format returned by
|
| 198 |
+
continued_fraction_periodic.
|
| 199 |
+
|
| 200 |
+
For quadratic irrationals, returns the largest solution found,
|
| 201 |
+
which is generally the one sought, if the fraction is in canonical
|
| 202 |
+
form (all terms positive except possibly the first).
|
| 203 |
+
|
| 204 |
+
Examples
|
| 205 |
+
========
|
| 206 |
+
|
| 207 |
+
>>> from sympy.ntheory.continued_fraction import continued_fraction_reduce
|
| 208 |
+
>>> continued_fraction_reduce([1, 2, 3, 4, 5])
|
| 209 |
+
225/157
|
| 210 |
+
>>> continued_fraction_reduce([-2, 1, 9, 7, 1, 2])
|
| 211 |
+
-256/233
|
| 212 |
+
>>> continued_fraction_reduce([2, 1, 2, 1, 1, 4, 1, 1, 6, 1, 1, 8]).n(10)
|
| 213 |
+
2.718281835
|
| 214 |
+
>>> continued_fraction_reduce([1, 4, 2, [3, 1]])
|
| 215 |
+
(sqrt(21) + 287)/238
|
| 216 |
+
>>> continued_fraction_reduce([[1]])
|
| 217 |
+
(1 + sqrt(5))/2
|
| 218 |
+
>>> from sympy.ntheory.continued_fraction import continued_fraction_periodic
|
| 219 |
+
>>> continued_fraction_reduce(continued_fraction_periodic(8, 5, 13))
|
| 220 |
+
(sqrt(13) + 8)/5
|
| 221 |
+
|
| 222 |
+
See Also
|
| 223 |
+
========
|
| 224 |
+
|
| 225 |
+
continued_fraction_periodic
|
| 226 |
+
|
| 227 |
+
"""
|
| 228 |
+
from sympy.solvers import solve
|
| 229 |
+
|
| 230 |
+
period = []
|
| 231 |
+
x = Dummy('x')
|
| 232 |
+
|
| 233 |
+
def untillist(cf):
|
| 234 |
+
for nxt in cf:
|
| 235 |
+
if isinstance(nxt, list):
|
| 236 |
+
period.extend(nxt)
|
| 237 |
+
yield x
|
| 238 |
+
break
|
| 239 |
+
yield nxt
|
| 240 |
+
|
| 241 |
+
a = S.Zero
|
| 242 |
+
for a in continued_fraction_convergents(untillist(cf)):
|
| 243 |
+
pass
|
| 244 |
+
|
| 245 |
+
if period:
|
| 246 |
+
y = Dummy('y')
|
| 247 |
+
solns = solve(continued_fraction_reduce(period + [y]) - y, y)
|
| 248 |
+
solns.sort()
|
| 249 |
+
pure = solns[-1]
|
| 250 |
+
rv = a.subs(x, pure).radsimp()
|
| 251 |
+
else:
|
| 252 |
+
rv = a
|
| 253 |
+
if rv.is_Add:
|
| 254 |
+
rv = factor_terms(rv)
|
| 255 |
+
if rv.is_Mul and rv.args[0] == -1:
|
| 256 |
+
rv = rv.func(*rv.args)
|
| 257 |
+
return rv
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
def continued_fraction_iterator(x):
|
| 261 |
+
"""
|
| 262 |
+
Return continued fraction expansion of x as iterator.
|
| 263 |
+
|
| 264 |
+
Examples
|
| 265 |
+
========
|
| 266 |
+
|
| 267 |
+
>>> from sympy import Rational, pi
|
| 268 |
+
>>> from sympy.ntheory.continued_fraction import continued_fraction_iterator
|
| 269 |
+
|
| 270 |
+
>>> list(continued_fraction_iterator(Rational(3, 8)))
|
| 271 |
+
[0, 2, 1, 2]
|
| 272 |
+
>>> list(continued_fraction_iterator(Rational(-3, 8)))
|
| 273 |
+
[-1, 1, 1, 1, 2]
|
| 274 |
+
|
| 275 |
+
>>> for i, v in enumerate(continued_fraction_iterator(pi)):
|
| 276 |
+
... if i > 7:
|
| 277 |
+
... break
|
| 278 |
+
... print(v)
|
| 279 |
+
3
|
| 280 |
+
7
|
| 281 |
+
15
|
| 282 |
+
1
|
| 283 |
+
292
|
| 284 |
+
1
|
| 285 |
+
1
|
| 286 |
+
1
|
| 287 |
+
|
| 288 |
+
References
|
| 289 |
+
==========
|
| 290 |
+
|
| 291 |
+
.. [1] https://en.wikipedia.org/wiki/Continued_fraction
|
| 292 |
+
|
| 293 |
+
"""
|
| 294 |
+
from sympy.functions import floor
|
| 295 |
+
while True:
|
| 296 |
+
i = floor(x)
|
| 297 |
+
yield i
|
| 298 |
+
x -= i
|
| 299 |
+
if not x:
|
| 300 |
+
break
|
| 301 |
+
x = 1/x
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
def continued_fraction_convergents(cf):
|
| 305 |
+
"""
|
| 306 |
+
Return an iterator over the convergents of a continued fraction (cf).
|
| 307 |
+
|
| 308 |
+
The parameter should be in either of the following to forms:
|
| 309 |
+
- A list of partial quotients, possibly with the last element being a list
|
| 310 |
+
of repeating partial quotients, such as might be returned by
|
| 311 |
+
continued_fraction and continued_fraction_periodic.
|
| 312 |
+
- An iterable returning successive partial quotients of the continued
|
| 313 |
+
fraction, such as might be returned by continued_fraction_iterator.
|
| 314 |
+
|
| 315 |
+
In computing the convergents, the continued fraction need not be strictly
|
| 316 |
+
in canonical form (all integers, all but the first positive).
|
| 317 |
+
Rational and negative elements may be present in the expansion.
|
| 318 |
+
|
| 319 |
+
Examples
|
| 320 |
+
========
|
| 321 |
+
|
| 322 |
+
>>> from sympy.core import pi
|
| 323 |
+
>>> from sympy import S
|
| 324 |
+
>>> from sympy.ntheory.continued_fraction import \
|
| 325 |
+
continued_fraction_convergents, continued_fraction_iterator
|
| 326 |
+
|
| 327 |
+
>>> list(continued_fraction_convergents([0, 2, 1, 2]))
|
| 328 |
+
[0, 1/2, 1/3, 3/8]
|
| 329 |
+
|
| 330 |
+
>>> list(continued_fraction_convergents([1, S('1/2'), -7, S('1/4')]))
|
| 331 |
+
[1, 3, 19/5, 7]
|
| 332 |
+
|
| 333 |
+
>>> it = continued_fraction_convergents(continued_fraction_iterator(pi))
|
| 334 |
+
>>> for n in range(7):
|
| 335 |
+
... print(next(it))
|
| 336 |
+
3
|
| 337 |
+
22/7
|
| 338 |
+
333/106
|
| 339 |
+
355/113
|
| 340 |
+
103993/33102
|
| 341 |
+
104348/33215
|
| 342 |
+
208341/66317
|
| 343 |
+
|
| 344 |
+
>>> it = continued_fraction_convergents([1, [1, 2]]) # sqrt(3)
|
| 345 |
+
>>> for n in range(7):
|
| 346 |
+
... print(next(it))
|
| 347 |
+
1
|
| 348 |
+
2
|
| 349 |
+
5/3
|
| 350 |
+
7/4
|
| 351 |
+
19/11
|
| 352 |
+
26/15
|
| 353 |
+
71/41
|
| 354 |
+
|
| 355 |
+
See Also
|
| 356 |
+
========
|
| 357 |
+
|
| 358 |
+
continued_fraction_iterator, continued_fraction, continued_fraction_periodic
|
| 359 |
+
|
| 360 |
+
"""
|
| 361 |
+
if isinstance(cf, list) and isinstance(cf[-1], list):
|
| 362 |
+
cf = itertools.chain(cf[:-1], itertools.cycle(cf[-1]))
|
| 363 |
+
p_2, q_2 = S.Zero, S.One
|
| 364 |
+
p_1, q_1 = S.One, S.Zero
|
| 365 |
+
for a in cf:
|
| 366 |
+
p, q = a*p_1 + p_2, a*q_1 + q_2
|
| 367 |
+
p_2, q_2 = p_1, q_1
|
| 368 |
+
p_1, q_1 = p, q
|
| 369 |
+
yield p/q
|
infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/egyptian_fraction.py
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.core.containers import Tuple
|
| 2 |
+
from sympy.core.numbers import (Integer, Rational)
|
| 3 |
+
from sympy.core.singleton import S
|
| 4 |
+
import sympy.polys
|
| 5 |
+
|
| 6 |
+
from math import gcd
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def egyptian_fraction(r, algorithm="Greedy"):
|
| 10 |
+
"""
|
| 11 |
+
Return the list of denominators of an Egyptian fraction
|
| 12 |
+
expansion [1]_ of the said rational `r`.
|
| 13 |
+
|
| 14 |
+
Parameters
|
| 15 |
+
==========
|
| 16 |
+
|
| 17 |
+
r : Rational or (p, q)
|
| 18 |
+
a positive rational number, ``p/q``.
|
| 19 |
+
algorithm : { "Greedy", "Graham Jewett", "Takenouchi", "Golomb" }, optional
|
| 20 |
+
Denotes the algorithm to be used (the default is "Greedy").
|
| 21 |
+
|
| 22 |
+
Examples
|
| 23 |
+
========
|
| 24 |
+
|
| 25 |
+
>>> from sympy import Rational
|
| 26 |
+
>>> from sympy.ntheory.egyptian_fraction import egyptian_fraction
|
| 27 |
+
>>> egyptian_fraction(Rational(3, 7))
|
| 28 |
+
[3, 11, 231]
|
| 29 |
+
>>> egyptian_fraction((3, 7), "Graham Jewett")
|
| 30 |
+
[7, 8, 9, 56, 57, 72, 3192]
|
| 31 |
+
>>> egyptian_fraction((3, 7), "Takenouchi")
|
| 32 |
+
[4, 7, 28]
|
| 33 |
+
>>> egyptian_fraction((3, 7), "Golomb")
|
| 34 |
+
[3, 15, 35]
|
| 35 |
+
>>> egyptian_fraction((11, 5), "Golomb")
|
| 36 |
+
[1, 2, 3, 4, 9, 234, 1118, 2580]
|
| 37 |
+
|
| 38 |
+
See Also
|
| 39 |
+
========
|
| 40 |
+
|
| 41 |
+
sympy.core.numbers.Rational
|
| 42 |
+
|
| 43 |
+
Notes
|
| 44 |
+
=====
|
| 45 |
+
|
| 46 |
+
Currently the following algorithms are supported:
|
| 47 |
+
|
| 48 |
+
1) Greedy Algorithm
|
| 49 |
+
|
| 50 |
+
Also called the Fibonacci-Sylvester algorithm [2]_.
|
| 51 |
+
At each step, extract the largest unit fraction less
|
| 52 |
+
than the target and replace the target with the remainder.
|
| 53 |
+
|
| 54 |
+
It has some distinct properties:
|
| 55 |
+
|
| 56 |
+
a) Given `p/q` in lowest terms, generates an expansion of maximum
|
| 57 |
+
length `p`. Even as the numerators get large, the number of
|
| 58 |
+
terms is seldom more than a handful.
|
| 59 |
+
|
| 60 |
+
b) Uses minimal memory.
|
| 61 |
+
|
| 62 |
+
c) The terms can blow up (standard examples of this are 5/121 and
|
| 63 |
+
31/311). The denominator is at most squared at each step
|
| 64 |
+
(doubly-exponential growth) and typically exhibits
|
| 65 |
+
singly-exponential growth.
|
| 66 |
+
|
| 67 |
+
2) Graham Jewett Algorithm
|
| 68 |
+
|
| 69 |
+
The algorithm suggested by the result of Graham and Jewett.
|
| 70 |
+
Note that this has a tendency to blow up: the length of the
|
| 71 |
+
resulting expansion is always ``2**(x/gcd(x, y)) - 1``. See [3]_.
|
| 72 |
+
|
| 73 |
+
3) Takenouchi Algorithm
|
| 74 |
+
|
| 75 |
+
The algorithm suggested by Takenouchi (1921).
|
| 76 |
+
Differs from the Graham-Jewett algorithm only in the handling
|
| 77 |
+
of duplicates. See [3]_.
|
| 78 |
+
|
| 79 |
+
4) Golomb's Algorithm
|
| 80 |
+
|
| 81 |
+
A method given by Golumb (1962), using modular arithmetic and
|
| 82 |
+
inverses. It yields the same results as a method using continued
|
| 83 |
+
fractions proposed by Bleicher (1972). See [4]_.
|
| 84 |
+
|
| 85 |
+
If the given rational is greater than or equal to 1, a greedy algorithm
|
| 86 |
+
of summing the harmonic sequence 1/1 + 1/2 + 1/3 + ... is used, taking
|
| 87 |
+
all the unit fractions of this sequence until adding one more would be
|
| 88 |
+
greater than the given number. This list of denominators is prefixed
|
| 89 |
+
to the result from the requested algorithm used on the remainder. For
|
| 90 |
+
example, if r is 8/3, using the Greedy algorithm, we get [1, 2, 3, 4,
|
| 91 |
+
5, 6, 7, 14, 420], where the beginning of the sequence, [1, 2, 3, 4, 5,
|
| 92 |
+
6, 7] is part of the harmonic sequence summing to 363/140, leaving a
|
| 93 |
+
remainder of 31/420, which yields [14, 420] by the Greedy algorithm.
|
| 94 |
+
The result of egyptian_fraction(Rational(8, 3), "Golomb") is [1, 2, 3,
|
| 95 |
+
4, 5, 6, 7, 14, 574, 2788, 6460, 11590, 33062, 113820], and so on.
|
| 96 |
+
|
| 97 |
+
References
|
| 98 |
+
==========
|
| 99 |
+
|
| 100 |
+
.. [1] https://en.wikipedia.org/wiki/Egyptian_fraction
|
| 101 |
+
.. [2] https://en.wikipedia.org/wiki/Greedy_algorithm_for_Egyptian_fractions
|
| 102 |
+
.. [3] https://www.ics.uci.edu/~eppstein/numth/egypt/conflict.html
|
| 103 |
+
.. [4] https://web.archive.org/web/20180413004012/https://ami.ektf.hu/uploads/papers/finalpdf/AMI_42_from129to134.pdf
|
| 104 |
+
|
| 105 |
+
"""
|
| 106 |
+
|
| 107 |
+
if not isinstance(r, Rational):
|
| 108 |
+
if isinstance(r, (Tuple, tuple)) and len(r) == 2:
|
| 109 |
+
r = Rational(*r)
|
| 110 |
+
else:
|
| 111 |
+
raise ValueError("Value must be a Rational or tuple of ints")
|
| 112 |
+
if r <= 0:
|
| 113 |
+
raise ValueError("Value must be positive")
|
| 114 |
+
|
| 115 |
+
# common cases that all methods agree on
|
| 116 |
+
x, y = r.as_numer_denom()
|
| 117 |
+
if y == 1 and x == 2:
|
| 118 |
+
return [Integer(i) for i in [1, 2, 3, 6]]
|
| 119 |
+
if x == y + 1:
|
| 120 |
+
return [S.One, y]
|
| 121 |
+
|
| 122 |
+
prefix, rem = egypt_harmonic(r)
|
| 123 |
+
if rem == 0:
|
| 124 |
+
return prefix
|
| 125 |
+
# work in Python ints
|
| 126 |
+
x, y = rem.p, rem.q
|
| 127 |
+
# assert x < y and gcd(x, y) = 1
|
| 128 |
+
|
| 129 |
+
if algorithm == "Greedy":
|
| 130 |
+
postfix = egypt_greedy(x, y)
|
| 131 |
+
elif algorithm == "Graham Jewett":
|
| 132 |
+
postfix = egypt_graham_jewett(x, y)
|
| 133 |
+
elif algorithm == "Takenouchi":
|
| 134 |
+
postfix = egypt_takenouchi(x, y)
|
| 135 |
+
elif algorithm == "Golomb":
|
| 136 |
+
postfix = egypt_golomb(x, y)
|
| 137 |
+
else:
|
| 138 |
+
raise ValueError("Entered invalid algorithm")
|
| 139 |
+
return prefix + [Integer(i) for i in postfix]
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def egypt_greedy(x, y):
|
| 143 |
+
# assumes gcd(x, y) == 1
|
| 144 |
+
if x == 1:
|
| 145 |
+
return [y]
|
| 146 |
+
else:
|
| 147 |
+
a = (-y) % x
|
| 148 |
+
b = y*(y//x + 1)
|
| 149 |
+
c = gcd(a, b)
|
| 150 |
+
if c > 1:
|
| 151 |
+
num, denom = a//c, b//c
|
| 152 |
+
else:
|
| 153 |
+
num, denom = a, b
|
| 154 |
+
return [y//x + 1] + egypt_greedy(num, denom)
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def egypt_graham_jewett(x, y):
|
| 158 |
+
# assumes gcd(x, y) == 1
|
| 159 |
+
l = [y] * x
|
| 160 |
+
|
| 161 |
+
# l is now a list of integers whose reciprocals sum to x/y.
|
| 162 |
+
# we shall now proceed to manipulate the elements of l without
|
| 163 |
+
# changing the reciprocated sum until all elements are unique.
|
| 164 |
+
|
| 165 |
+
while len(l) != len(set(l)):
|
| 166 |
+
l.sort() # so the list has duplicates. find a smallest pair
|
| 167 |
+
for i in range(len(l) - 1):
|
| 168 |
+
if l[i] == l[i + 1]:
|
| 169 |
+
break
|
| 170 |
+
# we have now identified a pair of identical
|
| 171 |
+
# elements: l[i] and l[i + 1].
|
| 172 |
+
# now comes the application of the result of graham and jewett:
|
| 173 |
+
l[i + 1] = l[i] + 1
|
| 174 |
+
# and we just iterate that until the list has no duplicates.
|
| 175 |
+
l.append(l[i]*(l[i] + 1))
|
| 176 |
+
return sorted(l)
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def egypt_takenouchi(x, y):
|
| 180 |
+
# assumes gcd(x, y) == 1
|
| 181 |
+
# special cases for 3/y
|
| 182 |
+
if x == 3:
|
| 183 |
+
if y % 2 == 0:
|
| 184 |
+
return [y//2, y]
|
| 185 |
+
i = (y - 1)//2
|
| 186 |
+
j = i + 1
|
| 187 |
+
k = j + i
|
| 188 |
+
return [j, k, j*k]
|
| 189 |
+
l = [y] * x
|
| 190 |
+
while len(l) != len(set(l)):
|
| 191 |
+
l.sort()
|
| 192 |
+
for i in range(len(l) - 1):
|
| 193 |
+
if l[i] == l[i + 1]:
|
| 194 |
+
break
|
| 195 |
+
k = l[i]
|
| 196 |
+
if k % 2 == 0:
|
| 197 |
+
l[i] = l[i] // 2
|
| 198 |
+
del l[i + 1]
|
| 199 |
+
else:
|
| 200 |
+
l[i], l[i + 1] = (k + 1)//2, k*(k + 1)//2
|
| 201 |
+
return sorted(l)
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
def egypt_golomb(x, y):
|
| 205 |
+
# assumes x < y and gcd(x, y) == 1
|
| 206 |
+
if x == 1:
|
| 207 |
+
return [y]
|
| 208 |
+
xp = sympy.polys.ZZ.invert(int(x), int(y))
|
| 209 |
+
rv = [xp*y]
|
| 210 |
+
rv.extend(egypt_golomb((x*xp - 1)//y, xp))
|
| 211 |
+
return sorted(rv)
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
def egypt_harmonic(r):
|
| 215 |
+
# assumes r is Rational
|
| 216 |
+
rv = []
|
| 217 |
+
d = S.One
|
| 218 |
+
acc = S.Zero
|
| 219 |
+
while acc + 1/d <= r:
|
| 220 |
+
acc += 1/d
|
| 221 |
+
rv.append(d)
|
| 222 |
+
d += 1
|
| 223 |
+
return (rv, r - acc)
|
infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/elliptic_curve.py
ADDED
|
@@ -0,0 +1,397 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.core.numbers import oo
|
| 2 |
+
from sympy.core.symbol import symbols
|
| 3 |
+
from sympy.polys.domains import FiniteField, QQ, RationalField, FF
|
| 4 |
+
from sympy.polys.polytools import Poly
|
| 5 |
+
from sympy.solvers.solvers import solve
|
| 6 |
+
from sympy.utilities.iterables import is_sequence
|
| 7 |
+
from sympy.utilities.misc import as_int
|
| 8 |
+
from .factor_ import divisors
|
| 9 |
+
from .residue_ntheory import polynomial_congruence
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class EllipticCurve:
|
| 13 |
+
"""
|
| 14 |
+
Create the following Elliptic Curve over domain.
|
| 15 |
+
|
| 16 |
+
`y^{2} + a_{1} x y + a_{3} y = x^{3} + a_{2} x^{2} + a_{4} x + a_{6}`
|
| 17 |
+
|
| 18 |
+
The default domain is ``QQ``. If no coefficient ``a1``, ``a2``, ``a3``,
|
| 19 |
+
is given then it creates a curve with the following form:
|
| 20 |
+
|
| 21 |
+
`y^{2} = x^{3} + a_{4} x + a_{6}`
|
| 22 |
+
|
| 23 |
+
Examples
|
| 24 |
+
========
|
| 25 |
+
|
| 26 |
+
References
|
| 27 |
+
==========
|
| 28 |
+
|
| 29 |
+
.. [1] J. Silverman "A Friendly Introduction to Number Theory" Third Edition
|
| 30 |
+
.. [2] https://mathworld.wolfram.com/EllipticDiscriminant.html
|
| 31 |
+
.. [3] G. Hardy, E. Wright "An Introduction to the Theory of Numbers" Sixth Edition
|
| 32 |
+
|
| 33 |
+
"""
|
| 34 |
+
|
| 35 |
+
def __init__(self, a4, a6, a1=0, a2=0, a3=0, modulus=0):
|
| 36 |
+
if modulus == 0:
|
| 37 |
+
domain = QQ
|
| 38 |
+
else:
|
| 39 |
+
domain = FF(modulus)
|
| 40 |
+
a1, a2, a3, a4, a6 = map(domain.convert, (a1, a2, a3, a4, a6))
|
| 41 |
+
self._domain = domain
|
| 42 |
+
self.modulus = modulus
|
| 43 |
+
# Calculate discriminant
|
| 44 |
+
b2 = a1**2 + 4 * a2
|
| 45 |
+
b4 = 2 * a4 + a1 * a3
|
| 46 |
+
b6 = a3**2 + 4 * a6
|
| 47 |
+
b8 = a1**2 * a6 + 4 * a2 * a6 - a1 * a3 * a4 + a2 * a3**2 - a4**2
|
| 48 |
+
self._b2, self._b4, self._b6, self._b8 = b2, b4, b6, b8
|
| 49 |
+
self._discrim = -b2**2 * b8 - 8 * b4**3 - 27 * b6**2 + 9 * b2 * b4 * b6
|
| 50 |
+
self._a1 = a1
|
| 51 |
+
self._a2 = a2
|
| 52 |
+
self._a3 = a3
|
| 53 |
+
self._a4 = a4
|
| 54 |
+
self._a6 = a6
|
| 55 |
+
x, y, z = symbols('x y z')
|
| 56 |
+
self.x, self.y, self.z = x, y, z
|
| 57 |
+
self._poly = Poly(y**2*z + a1*x*y*z + a3*y*z**2 - x**3 - a2*x**2*z - a4*x*z**2 - a6*z**3, domain=domain)
|
| 58 |
+
if isinstance(self._domain, FiniteField):
|
| 59 |
+
self._rank = 0
|
| 60 |
+
elif isinstance(self._domain, RationalField):
|
| 61 |
+
self._rank = None
|
| 62 |
+
|
| 63 |
+
def __call__(self, x, y, z=1):
|
| 64 |
+
return EllipticCurvePoint(x, y, z, self)
|
| 65 |
+
|
| 66 |
+
def __contains__(self, point):
|
| 67 |
+
if is_sequence(point):
|
| 68 |
+
if len(point) == 2:
|
| 69 |
+
z1 = 1
|
| 70 |
+
else:
|
| 71 |
+
z1 = point[2]
|
| 72 |
+
x1, y1 = point[:2]
|
| 73 |
+
elif isinstance(point, EllipticCurvePoint):
|
| 74 |
+
x1, y1, z1 = point.x, point.y, point.z
|
| 75 |
+
else:
|
| 76 |
+
raise ValueError('Invalid point.')
|
| 77 |
+
if self.characteristic == 0 and z1 == 0:
|
| 78 |
+
return True
|
| 79 |
+
return self._poly.subs({self.x: x1, self.y: y1, self.z: z1}) == 0
|
| 80 |
+
|
| 81 |
+
def __repr__(self):
|
| 82 |
+
return self._poly.__repr__()
|
| 83 |
+
|
| 84 |
+
def minimal(self):
|
| 85 |
+
"""
|
| 86 |
+
Return minimal Weierstrass equation.
|
| 87 |
+
|
| 88 |
+
Examples
|
| 89 |
+
========
|
| 90 |
+
|
| 91 |
+
>>> from sympy.ntheory.elliptic_curve import EllipticCurve
|
| 92 |
+
|
| 93 |
+
>>> e1 = EllipticCurve(-10, -20, 0, -1, 1)
|
| 94 |
+
>>> e1.minimal()
|
| 95 |
+
Poly(-x**3 + 13392*x*z**2 + y**2*z + 1080432*z**3, x, y, z, domain='QQ')
|
| 96 |
+
|
| 97 |
+
"""
|
| 98 |
+
char = self.characteristic
|
| 99 |
+
if char == 2:
|
| 100 |
+
return self
|
| 101 |
+
if char == 3:
|
| 102 |
+
return EllipticCurve(self._b4/2, self._b6/4, a2=self._b2/4, modulus=self.modulus)
|
| 103 |
+
c4 = self._b2**2 - 24*self._b4
|
| 104 |
+
c6 = -self._b2**3 + 36*self._b2*self._b4 - 216*self._b6
|
| 105 |
+
return EllipticCurve(-27*c4, -54*c6, modulus=self.modulus)
|
| 106 |
+
|
| 107 |
+
def points(self):
|
| 108 |
+
"""
|
| 109 |
+
Return points of curve over Finite Field.
|
| 110 |
+
|
| 111 |
+
Examples
|
| 112 |
+
========
|
| 113 |
+
|
| 114 |
+
>>> from sympy.ntheory.elliptic_curve import EllipticCurve
|
| 115 |
+
>>> e2 = EllipticCurve(1, 1, 1, 1, 1, modulus=5)
|
| 116 |
+
>>> e2.points()
|
| 117 |
+
{(0, 2), (1, 4), (2, 0), (2, 2), (3, 0), (3, 1), (4, 0)}
|
| 118 |
+
|
| 119 |
+
"""
|
| 120 |
+
|
| 121 |
+
char = self.characteristic
|
| 122 |
+
all_pt = set()
|
| 123 |
+
if char >= 1:
|
| 124 |
+
for i in range(char):
|
| 125 |
+
congruence_eq = self._poly.subs({self.x: i, self.z: 1}).expr
|
| 126 |
+
sol = polynomial_congruence(congruence_eq, char)
|
| 127 |
+
all_pt.update((i, num) for num in sol)
|
| 128 |
+
return all_pt
|
| 129 |
+
else:
|
| 130 |
+
raise ValueError("Infinitely many points")
|
| 131 |
+
|
| 132 |
+
def points_x(self, x):
|
| 133 |
+
"""Returns points on the curve for the given x-coordinate."""
|
| 134 |
+
pt = []
|
| 135 |
+
if self._domain == QQ:
|
| 136 |
+
for y in solve(self._poly.subs(self.x, x)):
|
| 137 |
+
pt.append((x, y))
|
| 138 |
+
else:
|
| 139 |
+
congruence_eq = self._poly.subs({self.x: x, self.z: 1}).expr
|
| 140 |
+
for y in polynomial_congruence(congruence_eq, self.characteristic):
|
| 141 |
+
pt.append((x, y))
|
| 142 |
+
return pt
|
| 143 |
+
|
| 144 |
+
def torsion_points(self):
|
| 145 |
+
"""
|
| 146 |
+
Return torsion points of curve over Rational number.
|
| 147 |
+
|
| 148 |
+
Return point objects those are finite order.
|
| 149 |
+
According to Nagell-Lutz theorem, torsion point p(x, y)
|
| 150 |
+
x and y are integers, either y = 0 or y**2 is divisor
|
| 151 |
+
of discriminent. According to Mazur's theorem, there are
|
| 152 |
+
at most 15 points in torsion collection.
|
| 153 |
+
|
| 154 |
+
Examples
|
| 155 |
+
========
|
| 156 |
+
|
| 157 |
+
>>> from sympy.ntheory.elliptic_curve import EllipticCurve
|
| 158 |
+
>>> e2 = EllipticCurve(-43, 166)
|
| 159 |
+
>>> sorted(e2.torsion_points())
|
| 160 |
+
[(-5, -16), (-5, 16), O, (3, -8), (3, 8), (11, -32), (11, 32)]
|
| 161 |
+
|
| 162 |
+
"""
|
| 163 |
+
if self.characteristic > 0:
|
| 164 |
+
raise ValueError("No torsion point for Finite Field.")
|
| 165 |
+
l = [EllipticCurvePoint.point_at_infinity(self)]
|
| 166 |
+
for xx in solve(self._poly.subs({self.y: 0, self.z: 1})):
|
| 167 |
+
if xx.is_rational:
|
| 168 |
+
l.append(self(xx, 0))
|
| 169 |
+
for i in divisors(self.discriminant, generator=True):
|
| 170 |
+
j = int(i**.5)
|
| 171 |
+
if j**2 == i:
|
| 172 |
+
for xx in solve(self._poly.subs({self.y: j, self.z: 1})):
|
| 173 |
+
if not xx.is_rational:
|
| 174 |
+
continue
|
| 175 |
+
p = self(xx, j)
|
| 176 |
+
if p.order() != oo:
|
| 177 |
+
l.extend([p, -p])
|
| 178 |
+
return l
|
| 179 |
+
|
| 180 |
+
@property
|
| 181 |
+
def characteristic(self):
|
| 182 |
+
"""
|
| 183 |
+
Return domain characteristic.
|
| 184 |
+
|
| 185 |
+
Examples
|
| 186 |
+
========
|
| 187 |
+
|
| 188 |
+
>>> from sympy.ntheory.elliptic_curve import EllipticCurve
|
| 189 |
+
>>> e2 = EllipticCurve(-43, 166)
|
| 190 |
+
>>> e2.characteristic
|
| 191 |
+
0
|
| 192 |
+
|
| 193 |
+
"""
|
| 194 |
+
return self._domain.characteristic()
|
| 195 |
+
|
| 196 |
+
@property
|
| 197 |
+
def discriminant(self):
|
| 198 |
+
"""
|
| 199 |
+
Return curve discriminant.
|
| 200 |
+
|
| 201 |
+
Examples
|
| 202 |
+
========
|
| 203 |
+
|
| 204 |
+
>>> from sympy.ntheory.elliptic_curve import EllipticCurve
|
| 205 |
+
>>> e2 = EllipticCurve(0, 17)
|
| 206 |
+
>>> e2.discriminant
|
| 207 |
+
-124848
|
| 208 |
+
|
| 209 |
+
"""
|
| 210 |
+
return int(self._discrim)
|
| 211 |
+
|
| 212 |
+
@property
|
| 213 |
+
def is_singular(self):
|
| 214 |
+
"""
|
| 215 |
+
Return True if curve discriminant is equal to zero.
|
| 216 |
+
"""
|
| 217 |
+
return self.discriminant == 0
|
| 218 |
+
|
| 219 |
+
@property
|
| 220 |
+
def j_invariant(self):
|
| 221 |
+
"""
|
| 222 |
+
Return curve j-invariant.
|
| 223 |
+
|
| 224 |
+
Examples
|
| 225 |
+
========
|
| 226 |
+
|
| 227 |
+
>>> from sympy.ntheory.elliptic_curve import EllipticCurve
|
| 228 |
+
>>> e1 = EllipticCurve(-2, 0, 0, 1, 1)
|
| 229 |
+
>>> e1.j_invariant
|
| 230 |
+
1404928/389
|
| 231 |
+
|
| 232 |
+
"""
|
| 233 |
+
c4 = self._b2**2 - 24*self._b4
|
| 234 |
+
return self._domain.to_sympy(c4**3 / self._discrim)
|
| 235 |
+
|
| 236 |
+
@property
|
| 237 |
+
def order(self):
|
| 238 |
+
"""
|
| 239 |
+
Number of points in Finite field.
|
| 240 |
+
|
| 241 |
+
Examples
|
| 242 |
+
========
|
| 243 |
+
|
| 244 |
+
>>> from sympy.ntheory.elliptic_curve import EllipticCurve
|
| 245 |
+
>>> e2 = EllipticCurve(1, 0, modulus=19)
|
| 246 |
+
>>> e2.order
|
| 247 |
+
19
|
| 248 |
+
|
| 249 |
+
"""
|
| 250 |
+
if self.characteristic == 0:
|
| 251 |
+
raise NotImplementedError("Still not implemented")
|
| 252 |
+
return len(self.points())
|
| 253 |
+
|
| 254 |
+
@property
|
| 255 |
+
def rank(self):
|
| 256 |
+
"""
|
| 257 |
+
Number of independent points of infinite order.
|
| 258 |
+
|
| 259 |
+
For Finite field, it must be 0.
|
| 260 |
+
"""
|
| 261 |
+
if self._rank is not None:
|
| 262 |
+
return self._rank
|
| 263 |
+
raise NotImplementedError("Still not implemented")
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
class EllipticCurvePoint:
|
| 267 |
+
"""
|
| 268 |
+
Point of Elliptic Curve
|
| 269 |
+
|
| 270 |
+
Examples
|
| 271 |
+
========
|
| 272 |
+
|
| 273 |
+
>>> from sympy.ntheory.elliptic_curve import EllipticCurve
|
| 274 |
+
>>> e1 = EllipticCurve(-17, 16)
|
| 275 |
+
>>> p1 = e1(0, -4, 1)
|
| 276 |
+
>>> p2 = e1(1, 0)
|
| 277 |
+
>>> p1 + p2
|
| 278 |
+
(15, -56)
|
| 279 |
+
>>> e3 = EllipticCurve(-1, 9)
|
| 280 |
+
>>> e3(1, -3) * 3
|
| 281 |
+
(664/169, 17811/2197)
|
| 282 |
+
>>> (e3(1, -3) * 3).order()
|
| 283 |
+
oo
|
| 284 |
+
>>> e2 = EllipticCurve(-2, 0, 0, 1, 1)
|
| 285 |
+
>>> p = e2(-1,1)
|
| 286 |
+
>>> q = e2(0, -1)
|
| 287 |
+
>>> p+q
|
| 288 |
+
(4, 8)
|
| 289 |
+
>>> p-q
|
| 290 |
+
(1, 0)
|
| 291 |
+
>>> 3*p-5*q
|
| 292 |
+
(328/361, -2800/6859)
|
| 293 |
+
"""
|
| 294 |
+
|
| 295 |
+
@staticmethod
|
| 296 |
+
def point_at_infinity(curve):
|
| 297 |
+
return EllipticCurvePoint(0, 1, 0, curve)
|
| 298 |
+
|
| 299 |
+
def __init__(self, x, y, z, curve):
|
| 300 |
+
dom = curve._domain.convert
|
| 301 |
+
self.x = dom(x)
|
| 302 |
+
self.y = dom(y)
|
| 303 |
+
self.z = dom(z)
|
| 304 |
+
self._curve = curve
|
| 305 |
+
self._domain = self._curve._domain
|
| 306 |
+
if not self._curve.__contains__(self):
|
| 307 |
+
raise ValueError("The curve does not contain this point")
|
| 308 |
+
|
| 309 |
+
def __add__(self, p):
|
| 310 |
+
if self.z == 0:
|
| 311 |
+
return p
|
| 312 |
+
if p.z == 0:
|
| 313 |
+
return self
|
| 314 |
+
x1, y1 = self.x/self.z, self.y/self.z
|
| 315 |
+
x2, y2 = p.x/p.z, p.y/p.z
|
| 316 |
+
a1 = self._curve._a1
|
| 317 |
+
a2 = self._curve._a2
|
| 318 |
+
a3 = self._curve._a3
|
| 319 |
+
a4 = self._curve._a4
|
| 320 |
+
a6 = self._curve._a6
|
| 321 |
+
if x1 != x2:
|
| 322 |
+
slope = (y1 - y2) / (x1 - x2)
|
| 323 |
+
yint = (y1 * x2 - y2 * x1) / (x2 - x1)
|
| 324 |
+
else:
|
| 325 |
+
if (y1 + y2) == 0:
|
| 326 |
+
return self.point_at_infinity(self._curve)
|
| 327 |
+
slope = (3 * x1**2 + 2*a2*x1 + a4 - a1*y1) / (a1 * x1 + a3 + 2 * y1)
|
| 328 |
+
yint = (-x1**3 + a4*x1 + 2*a6 - a3*y1) / (a1*x1 + a3 + 2*y1)
|
| 329 |
+
x3 = slope**2 + a1*slope - a2 - x1 - x2
|
| 330 |
+
y3 = -(slope + a1) * x3 - yint - a3
|
| 331 |
+
return self._curve(x3, y3, 1)
|
| 332 |
+
|
| 333 |
+
def __lt__(self, other):
|
| 334 |
+
return (self.x, self.y, self.z) < (other.x, other.y, other.z)
|
| 335 |
+
|
| 336 |
+
def __mul__(self, n):
|
| 337 |
+
n = as_int(n)
|
| 338 |
+
r = self.point_at_infinity(self._curve)
|
| 339 |
+
if n == 0:
|
| 340 |
+
return r
|
| 341 |
+
if n < 0:
|
| 342 |
+
return -self * -n
|
| 343 |
+
p = self
|
| 344 |
+
while n:
|
| 345 |
+
if n & 1:
|
| 346 |
+
r = r + p
|
| 347 |
+
n >>= 1
|
| 348 |
+
p = p + p
|
| 349 |
+
return r
|
| 350 |
+
|
| 351 |
+
def __rmul__(self, n):
|
| 352 |
+
return self * n
|
| 353 |
+
|
| 354 |
+
def __neg__(self):
|
| 355 |
+
return EllipticCurvePoint(self.x, -self.y - self._curve._a1*self.x - self._curve._a3, self.z, self._curve)
|
| 356 |
+
|
| 357 |
+
def __repr__(self):
|
| 358 |
+
if self.z == 0:
|
| 359 |
+
return 'O'
|
| 360 |
+
dom = self._curve._domain
|
| 361 |
+
try:
|
| 362 |
+
return '({}, {})'.format(dom.to_sympy(self.x), dom.to_sympy(self.y))
|
| 363 |
+
except TypeError:
|
| 364 |
+
pass
|
| 365 |
+
return '({}, {})'.format(self.x, self.y)
|
| 366 |
+
|
| 367 |
+
def __sub__(self, other):
|
| 368 |
+
return self.__add__(-other)
|
| 369 |
+
|
| 370 |
+
def order(self):
|
| 371 |
+
"""
|
| 372 |
+
Return point order n where nP = 0.
|
| 373 |
+
|
| 374 |
+
"""
|
| 375 |
+
if self.z == 0:
|
| 376 |
+
return 1
|
| 377 |
+
if self.y == 0: # P = -P
|
| 378 |
+
return 2
|
| 379 |
+
p = self * 2
|
| 380 |
+
if p.y == -self.y: # 2P = -P
|
| 381 |
+
return 3
|
| 382 |
+
i = 2
|
| 383 |
+
if self._domain != QQ:
|
| 384 |
+
while int(p.x) == p.x and int(p.y) == p.y:
|
| 385 |
+
p = self + p
|
| 386 |
+
i += 1
|
| 387 |
+
if p.z == 0:
|
| 388 |
+
return i
|
| 389 |
+
return oo
|
| 390 |
+
while p.x.numerator == p.x and p.y.numerator == p.y:
|
| 391 |
+
p = self + p
|
| 392 |
+
i += 1
|
| 393 |
+
if i > 12:
|
| 394 |
+
return oo
|
| 395 |
+
if p.z == 0:
|
| 396 |
+
return i
|
| 397 |
+
return oo
|
infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/factor_.py
ADDED
|
@@ -0,0 +1,2668 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Integer factorization
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from collections import defaultdict
|
| 6 |
+
import math
|
| 7 |
+
|
| 8 |
+
from sympy.core.containers import Dict
|
| 9 |
+
from sympy.core.mul import Mul
|
| 10 |
+
from sympy.core.numbers import Rational, Integer
|
| 11 |
+
from sympy.core.intfunc import num_digits
|
| 12 |
+
from sympy.core.power import Pow
|
| 13 |
+
from sympy.core.random import _randint
|
| 14 |
+
from sympy.core.singleton import S
|
| 15 |
+
from sympy.external.gmpy import (SYMPY_INTS, gcd, sqrt as isqrt,
|
| 16 |
+
sqrtrem, iroot, bit_scan1, remove)
|
| 17 |
+
from .primetest import isprime, MERSENNE_PRIME_EXPONENTS, is_mersenne_prime
|
| 18 |
+
from .generate import sieve, primerange, nextprime
|
| 19 |
+
from .digits import digits
|
| 20 |
+
from sympy.utilities.decorator import deprecated
|
| 21 |
+
from sympy.utilities.iterables import flatten
|
| 22 |
+
from sympy.utilities.misc import as_int, filldedent
|
| 23 |
+
from .ecm import _ecm_one_factor
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def smoothness(n):
|
| 27 |
+
"""
|
| 28 |
+
Return the B-smooth and B-power smooth values of n.
|
| 29 |
+
|
| 30 |
+
The smoothness of n is the largest prime factor of n; the power-
|
| 31 |
+
smoothness is the largest divisor raised to its multiplicity.
|
| 32 |
+
|
| 33 |
+
Examples
|
| 34 |
+
========
|
| 35 |
+
|
| 36 |
+
>>> from sympy.ntheory.factor_ import smoothness
|
| 37 |
+
>>> smoothness(2**7*3**2)
|
| 38 |
+
(3, 128)
|
| 39 |
+
>>> smoothness(2**4*13)
|
| 40 |
+
(13, 16)
|
| 41 |
+
>>> smoothness(2)
|
| 42 |
+
(2, 2)
|
| 43 |
+
|
| 44 |
+
See Also
|
| 45 |
+
========
|
| 46 |
+
|
| 47 |
+
factorint, smoothness_p
|
| 48 |
+
"""
|
| 49 |
+
|
| 50 |
+
if n == 1:
|
| 51 |
+
return (1, 1) # not prime, but otherwise this causes headaches
|
| 52 |
+
facs = factorint(n)
|
| 53 |
+
return max(facs), max(m**facs[m] for m in facs)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def smoothness_p(n, m=-1, power=0, visual=None):
|
| 57 |
+
"""
|
| 58 |
+
Return a list of [m, (p, (M, sm(p + m), psm(p + m)))...]
|
| 59 |
+
where:
|
| 60 |
+
|
| 61 |
+
1. p**M is the base-p divisor of n
|
| 62 |
+
2. sm(p + m) is the smoothness of p + m (m = -1 by default)
|
| 63 |
+
3. psm(p + m) is the power smoothness of p + m
|
| 64 |
+
|
| 65 |
+
The list is sorted according to smoothness (default) or by power smoothness
|
| 66 |
+
if power=1.
|
| 67 |
+
|
| 68 |
+
The smoothness of the numbers to the left (m = -1) or right (m = 1) of a
|
| 69 |
+
factor govern the results that are obtained from the p +/- 1 type factoring
|
| 70 |
+
methods.
|
| 71 |
+
|
| 72 |
+
>>> from sympy.ntheory.factor_ import smoothness_p, factorint
|
| 73 |
+
>>> smoothness_p(10431, m=1)
|
| 74 |
+
(1, [(3, (2, 2, 4)), (19, (1, 5, 5)), (61, (1, 31, 31))])
|
| 75 |
+
>>> smoothness_p(10431)
|
| 76 |
+
(-1, [(3, (2, 2, 2)), (19, (1, 3, 9)), (61, (1, 5, 5))])
|
| 77 |
+
>>> smoothness_p(10431, power=1)
|
| 78 |
+
(-1, [(3, (2, 2, 2)), (61, (1, 5, 5)), (19, (1, 3, 9))])
|
| 79 |
+
|
| 80 |
+
If visual=True then an annotated string will be returned:
|
| 81 |
+
|
| 82 |
+
>>> print(smoothness_p(21477639576571, visual=1))
|
| 83 |
+
p**i=4410317**1 has p-1 B=1787, B-pow=1787
|
| 84 |
+
p**i=4869863**1 has p-1 B=2434931, B-pow=2434931
|
| 85 |
+
|
| 86 |
+
This string can also be generated directly from a factorization dictionary
|
| 87 |
+
and vice versa:
|
| 88 |
+
|
| 89 |
+
>>> factorint(17*9)
|
| 90 |
+
{3: 2, 17: 1}
|
| 91 |
+
>>> smoothness_p(_)
|
| 92 |
+
'p**i=3**2 has p-1 B=2, B-pow=2\\np**i=17**1 has p-1 B=2, B-pow=16'
|
| 93 |
+
>>> smoothness_p(_)
|
| 94 |
+
{3: 2, 17: 1}
|
| 95 |
+
|
| 96 |
+
The table of the output logic is:
|
| 97 |
+
|
| 98 |
+
====== ====== ======= =======
|
| 99 |
+
| Visual
|
| 100 |
+
------ ----------------------
|
| 101 |
+
Input True False other
|
| 102 |
+
====== ====== ======= =======
|
| 103 |
+
dict str tuple str
|
| 104 |
+
str str tuple dict
|
| 105 |
+
tuple str tuple str
|
| 106 |
+
n str tuple tuple
|
| 107 |
+
mul str tuple tuple
|
| 108 |
+
====== ====== ======= =======
|
| 109 |
+
|
| 110 |
+
See Also
|
| 111 |
+
========
|
| 112 |
+
|
| 113 |
+
factorint, smoothness
|
| 114 |
+
"""
|
| 115 |
+
|
| 116 |
+
# visual must be True, False or other (stored as None)
|
| 117 |
+
if visual in (1, 0):
|
| 118 |
+
visual = bool(visual)
|
| 119 |
+
elif visual not in (True, False):
|
| 120 |
+
visual = None
|
| 121 |
+
|
| 122 |
+
if isinstance(n, str):
|
| 123 |
+
if visual:
|
| 124 |
+
return n
|
| 125 |
+
d = {}
|
| 126 |
+
for li in n.splitlines():
|
| 127 |
+
k, v = [int(i) for i in
|
| 128 |
+
li.split('has')[0].split('=')[1].split('**')]
|
| 129 |
+
d[k] = v
|
| 130 |
+
if visual is not True and visual is not False:
|
| 131 |
+
return d
|
| 132 |
+
return smoothness_p(d, visual=False)
|
| 133 |
+
elif not isinstance(n, tuple):
|
| 134 |
+
facs = factorint(n, visual=False)
|
| 135 |
+
|
| 136 |
+
if power:
|
| 137 |
+
k = -1
|
| 138 |
+
else:
|
| 139 |
+
k = 1
|
| 140 |
+
if isinstance(n, tuple):
|
| 141 |
+
rv = n
|
| 142 |
+
else:
|
| 143 |
+
rv = (m, sorted([(f,
|
| 144 |
+
tuple([M] + list(smoothness(f + m))))
|
| 145 |
+
for f, M in list(facs.items())],
|
| 146 |
+
key=lambda x: (x[1][k], x[0])))
|
| 147 |
+
|
| 148 |
+
if visual is False or (visual is not True) and (type(n) in [int, Mul]):
|
| 149 |
+
return rv
|
| 150 |
+
lines = []
|
| 151 |
+
for dat in rv[1]:
|
| 152 |
+
dat = flatten(dat)
|
| 153 |
+
dat.insert(2, m)
|
| 154 |
+
lines.append('p**i=%i**%i has p%+i B=%i, B-pow=%i' % tuple(dat))
|
| 155 |
+
return '\n'.join(lines)
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def multiplicity(p, n):
|
| 159 |
+
"""
|
| 160 |
+
Find the greatest integer m such that p**m divides n.
|
| 161 |
+
|
| 162 |
+
Examples
|
| 163 |
+
========
|
| 164 |
+
|
| 165 |
+
>>> from sympy import multiplicity, Rational
|
| 166 |
+
>>> [multiplicity(5, n) for n in [8, 5, 25, 125, 250]]
|
| 167 |
+
[0, 1, 2, 3, 3]
|
| 168 |
+
>>> multiplicity(3, Rational(1, 9))
|
| 169 |
+
-2
|
| 170 |
+
|
| 171 |
+
Note: when checking for the multiplicity of a number in a
|
| 172 |
+
large factorial it is most efficient to send it as an unevaluated
|
| 173 |
+
factorial or to call ``multiplicity_in_factorial`` directly:
|
| 174 |
+
|
| 175 |
+
>>> from sympy.ntheory import multiplicity_in_factorial
|
| 176 |
+
>>> from sympy import factorial
|
| 177 |
+
>>> p = factorial(25)
|
| 178 |
+
>>> n = 2**100
|
| 179 |
+
>>> nfac = factorial(n, evaluate=False)
|
| 180 |
+
>>> multiplicity(p, nfac)
|
| 181 |
+
52818775009509558395695966887
|
| 182 |
+
>>> _ == multiplicity_in_factorial(p, n)
|
| 183 |
+
True
|
| 184 |
+
|
| 185 |
+
See Also
|
| 186 |
+
========
|
| 187 |
+
|
| 188 |
+
trailing
|
| 189 |
+
|
| 190 |
+
"""
|
| 191 |
+
try:
|
| 192 |
+
p, n = as_int(p), as_int(n)
|
| 193 |
+
except ValueError:
|
| 194 |
+
from sympy.functions.combinatorial.factorials import factorial
|
| 195 |
+
if all(isinstance(i, (SYMPY_INTS, Rational)) for i in (p, n)):
|
| 196 |
+
p = Rational(p)
|
| 197 |
+
n = Rational(n)
|
| 198 |
+
if p.q == 1:
|
| 199 |
+
if n.p == 1:
|
| 200 |
+
return -multiplicity(p.p, n.q)
|
| 201 |
+
return multiplicity(p.p, n.p) - multiplicity(p.p, n.q)
|
| 202 |
+
elif p.p == 1:
|
| 203 |
+
return multiplicity(p.q, n.q)
|
| 204 |
+
else:
|
| 205 |
+
like = min(
|
| 206 |
+
multiplicity(p.p, n.p),
|
| 207 |
+
multiplicity(p.q, n.q))
|
| 208 |
+
cross = min(
|
| 209 |
+
multiplicity(p.q, n.p),
|
| 210 |
+
multiplicity(p.p, n.q))
|
| 211 |
+
return like - cross
|
| 212 |
+
elif (isinstance(p, (SYMPY_INTS, Integer)) and
|
| 213 |
+
isinstance(n, factorial) and
|
| 214 |
+
isinstance(n.args[0], Integer) and
|
| 215 |
+
n.args[0] >= 0):
|
| 216 |
+
return multiplicity_in_factorial(p, n.args[0])
|
| 217 |
+
raise ValueError('expecting ints or fractions, got %s and %s' % (p, n))
|
| 218 |
+
|
| 219 |
+
if n == 0:
|
| 220 |
+
raise ValueError('no such integer exists: multiplicity of %s is not-defined' %(n))
|
| 221 |
+
return remove(n, p)[1]
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
def multiplicity_in_factorial(p, n):
|
| 225 |
+
"""return the largest integer ``m`` such that ``p**m`` divides ``n!``
|
| 226 |
+
without calculating the factorial of ``n``.
|
| 227 |
+
|
| 228 |
+
Parameters
|
| 229 |
+
==========
|
| 230 |
+
|
| 231 |
+
p : Integer
|
| 232 |
+
positive integer
|
| 233 |
+
n : Integer
|
| 234 |
+
non-negative integer
|
| 235 |
+
|
| 236 |
+
Examples
|
| 237 |
+
========
|
| 238 |
+
|
| 239 |
+
>>> from sympy.ntheory import multiplicity_in_factorial
|
| 240 |
+
>>> from sympy import factorial
|
| 241 |
+
|
| 242 |
+
>>> multiplicity_in_factorial(2, 3)
|
| 243 |
+
1
|
| 244 |
+
|
| 245 |
+
An instructive use of this is to tell how many trailing zeros
|
| 246 |
+
a given factorial has. For example, there are 6 in 25!:
|
| 247 |
+
|
| 248 |
+
>>> factorial(25)
|
| 249 |
+
15511210043330985984000000
|
| 250 |
+
>>> multiplicity_in_factorial(10, 25)
|
| 251 |
+
6
|
| 252 |
+
|
| 253 |
+
For large factorials, it is much faster/feasible to use
|
| 254 |
+
this function rather than computing the actual factorial:
|
| 255 |
+
|
| 256 |
+
>>> multiplicity_in_factorial(factorial(25), 2**100)
|
| 257 |
+
52818775009509558395695966887
|
| 258 |
+
|
| 259 |
+
See Also
|
| 260 |
+
========
|
| 261 |
+
|
| 262 |
+
multiplicity
|
| 263 |
+
|
| 264 |
+
"""
|
| 265 |
+
|
| 266 |
+
p, n = as_int(p), as_int(n)
|
| 267 |
+
|
| 268 |
+
if p <= 0:
|
| 269 |
+
raise ValueError('expecting positive integer got %s' % p )
|
| 270 |
+
|
| 271 |
+
if n < 0:
|
| 272 |
+
raise ValueError('expecting non-negative integer got %s' % n )
|
| 273 |
+
|
| 274 |
+
# keep only the largest of a given multiplicity since those
|
| 275 |
+
# of a given multiplicity will be goverened by the behavior
|
| 276 |
+
# of the largest factor
|
| 277 |
+
f = defaultdict(int)
|
| 278 |
+
for k, v in factorint(p).items():
|
| 279 |
+
f[v] = max(k, f[v])
|
| 280 |
+
# multiplicity of p in n! depends on multiplicity
|
| 281 |
+
# of prime `k` in p, so we floor divide by `v`
|
| 282 |
+
# and keep it if smaller than the multiplicity of p
|
| 283 |
+
# seen so far
|
| 284 |
+
return min((n + k - sum(digits(n, k)))//(k - 1)//v for v, k in f.items())
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
def _perfect_power(n, next_p=2):
|
| 288 |
+
""" Return integers ``(b, e)`` such that ``n == b**e`` if ``n`` is a unique
|
| 289 |
+
perfect power with ``e > 1``, else ``False`` (e.g. 1 is not a perfect power).
|
| 290 |
+
|
| 291 |
+
Explanation
|
| 292 |
+
===========
|
| 293 |
+
|
| 294 |
+
This is a low-level helper for ``perfect_power``, for internal use.
|
| 295 |
+
|
| 296 |
+
Parameters
|
| 297 |
+
==========
|
| 298 |
+
|
| 299 |
+
n : int
|
| 300 |
+
assume that n is a nonnegative integer
|
| 301 |
+
next_p : int
|
| 302 |
+
Assume that n has no factor less than next_p.
|
| 303 |
+
i.e., all(n % p for p in range(2, next_p)) is True
|
| 304 |
+
|
| 305 |
+
Examples
|
| 306 |
+
========
|
| 307 |
+
>>> from sympy.ntheory.factor_ import _perfect_power
|
| 308 |
+
>>> _perfect_power(16)
|
| 309 |
+
(2, 4)
|
| 310 |
+
>>> _perfect_power(17)
|
| 311 |
+
False
|
| 312 |
+
|
| 313 |
+
"""
|
| 314 |
+
if n <= 3:
|
| 315 |
+
return False
|
| 316 |
+
|
| 317 |
+
factors = {}
|
| 318 |
+
g = 0
|
| 319 |
+
multi = 1
|
| 320 |
+
|
| 321 |
+
def done(n, factors, g, multi):
|
| 322 |
+
g = gcd(g, multi)
|
| 323 |
+
if g == 1:
|
| 324 |
+
return False
|
| 325 |
+
factors[n] = multi
|
| 326 |
+
return math.prod(p**(e//g) for p, e in factors.items()), g
|
| 327 |
+
|
| 328 |
+
# If n is small, only trial factoring is faster
|
| 329 |
+
if n <= 1_000_000:
|
| 330 |
+
n = _factorint_small(factors, n, 1_000, 1_000, next_p)[0]
|
| 331 |
+
if n > 1:
|
| 332 |
+
return False
|
| 333 |
+
g = gcd(*factors.values())
|
| 334 |
+
if g == 1:
|
| 335 |
+
return False
|
| 336 |
+
return math.prod(p**(e//g) for p, e in factors.items()), g
|
| 337 |
+
|
| 338 |
+
# divide by 2
|
| 339 |
+
if next_p < 3:
|
| 340 |
+
g = bit_scan1(n)
|
| 341 |
+
if g:
|
| 342 |
+
if g == 1:
|
| 343 |
+
return False
|
| 344 |
+
n >>= g
|
| 345 |
+
factors[2] = g
|
| 346 |
+
if n == 1:
|
| 347 |
+
return 2, g
|
| 348 |
+
else:
|
| 349 |
+
# If `m**g`, then we have found perfect power.
|
| 350 |
+
# Otherwise, there is no possibility of perfect power, especially if `g` is prime.
|
| 351 |
+
m, _exact = iroot(n, g)
|
| 352 |
+
if _exact:
|
| 353 |
+
return 2*m, g
|
| 354 |
+
elif isprime(g):
|
| 355 |
+
return False
|
| 356 |
+
next_p = 3
|
| 357 |
+
|
| 358 |
+
# square number?
|
| 359 |
+
while n & 7 == 1: # n % 8 == 1:
|
| 360 |
+
m, _exact = iroot(n, 2)
|
| 361 |
+
if _exact:
|
| 362 |
+
n = m
|
| 363 |
+
multi <<= 1
|
| 364 |
+
else:
|
| 365 |
+
break
|
| 366 |
+
if n < next_p**3:
|
| 367 |
+
return done(n, factors, g, multi)
|
| 368 |
+
|
| 369 |
+
# trial factoring
|
| 370 |
+
# Since the maximum value an exponent can take is `log_{next_p}(n)`,
|
| 371 |
+
# the number of exponents to be checked can be reduced by performing a trial factoring.
|
| 372 |
+
# The value of `tf_max` needs more consideration.
|
| 373 |
+
tf_max = n.bit_length()//27 + 24
|
| 374 |
+
if next_p < tf_max:
|
| 375 |
+
for p in primerange(next_p, tf_max):
|
| 376 |
+
m, t = remove(n, p)
|
| 377 |
+
if t:
|
| 378 |
+
n = m
|
| 379 |
+
t *= multi
|
| 380 |
+
_g = gcd(g, t)
|
| 381 |
+
if _g == 1:
|
| 382 |
+
return False
|
| 383 |
+
factors[p] = t
|
| 384 |
+
if n == 1:
|
| 385 |
+
return math.prod(p**(e//_g)
|
| 386 |
+
for p, e in factors.items()), _g
|
| 387 |
+
elif g == 0 or _g < g: # If g is updated
|
| 388 |
+
g = _g
|
| 389 |
+
m, _exact = iroot(n**multi, g)
|
| 390 |
+
if _exact:
|
| 391 |
+
return m * math.prod(p**(e//g)
|
| 392 |
+
for p, e in factors.items()), g
|
| 393 |
+
elif isprime(g):
|
| 394 |
+
return False
|
| 395 |
+
next_p = tf_max
|
| 396 |
+
if n < next_p**3:
|
| 397 |
+
return done(n, factors, g, multi)
|
| 398 |
+
|
| 399 |
+
# check iroot
|
| 400 |
+
if g:
|
| 401 |
+
# If g is non-zero, the exponent is a divisor of g.
|
| 402 |
+
# 2 can be omitted since it has already been checked.
|
| 403 |
+
prime_iter = sorted(factorint(g >> bit_scan1(g)).keys())
|
| 404 |
+
else:
|
| 405 |
+
# The maximum possible value of the exponent is `log_{next_p}(n)`.
|
| 406 |
+
# To compensate for the presence of computational error, 2 is added.
|
| 407 |
+
prime_iter = primerange(3, int(math.log(n, next_p)) + 2)
|
| 408 |
+
logn = math.log2(n)
|
| 409 |
+
threshold = logn / 40 # Threshold for direct calculation
|
| 410 |
+
for p in prime_iter:
|
| 411 |
+
if threshold < p:
|
| 412 |
+
# If p is large, find the power root p directly without `iroot`.
|
| 413 |
+
while True:
|
| 414 |
+
b = pow(2, logn / p)
|
| 415 |
+
rb = int(b + 0.5)
|
| 416 |
+
if abs(rb - b) < 0.01 and rb**p == n:
|
| 417 |
+
n = rb
|
| 418 |
+
multi *= p
|
| 419 |
+
logn = math.log2(n)
|
| 420 |
+
else:
|
| 421 |
+
break
|
| 422 |
+
else:
|
| 423 |
+
while True:
|
| 424 |
+
m, _exact = iroot(n, p)
|
| 425 |
+
if _exact:
|
| 426 |
+
n = m
|
| 427 |
+
multi *= p
|
| 428 |
+
logn = math.log2(n)
|
| 429 |
+
else:
|
| 430 |
+
break
|
| 431 |
+
if n < next_p**(p + 2):
|
| 432 |
+
break
|
| 433 |
+
return done(n, factors, g, multi)
|
| 434 |
+
|
| 435 |
+
|
| 436 |
+
def perfect_power(n, candidates=None, big=True, factor=True):
|
| 437 |
+
"""
|
| 438 |
+
Return ``(b, e)`` such that ``n`` == ``b**e`` if ``n`` is a unique
|
| 439 |
+
perfect power with ``e > 1``, else ``False`` (e.g. 1 is not a
|
| 440 |
+
perfect power). A ValueError is raised if ``n`` is not Rational.
|
| 441 |
+
|
| 442 |
+
By default, the base is recursively decomposed and the exponents
|
| 443 |
+
collected so the largest possible ``e`` is sought. If ``big=False``
|
| 444 |
+
then the smallest possible ``e`` (thus prime) will be chosen.
|
| 445 |
+
|
| 446 |
+
If ``factor=True`` then simultaneous factorization of ``n`` is
|
| 447 |
+
attempted since finding a factor indicates the only possible root
|
| 448 |
+
for ``n``. This is True by default since only a few small factors will
|
| 449 |
+
be tested in the course of searching for the perfect power.
|
| 450 |
+
|
| 451 |
+
The use of ``candidates`` is primarily for internal use; if provided,
|
| 452 |
+
False will be returned if ``n`` cannot be written as a power with one
|
| 453 |
+
of the candidates as an exponent and factoring (beyond testing for
|
| 454 |
+
a factor of 2) will not be attempted.
|
| 455 |
+
|
| 456 |
+
Examples
|
| 457 |
+
========
|
| 458 |
+
|
| 459 |
+
>>> from sympy import perfect_power, Rational
|
| 460 |
+
>>> perfect_power(16)
|
| 461 |
+
(2, 4)
|
| 462 |
+
>>> perfect_power(16, big=False)
|
| 463 |
+
(4, 2)
|
| 464 |
+
|
| 465 |
+
Negative numbers can only have odd perfect powers:
|
| 466 |
+
|
| 467 |
+
>>> perfect_power(-4)
|
| 468 |
+
False
|
| 469 |
+
>>> perfect_power(-8)
|
| 470 |
+
(-2, 3)
|
| 471 |
+
|
| 472 |
+
Rationals are also recognized:
|
| 473 |
+
|
| 474 |
+
>>> perfect_power(Rational(1, 2)**3)
|
| 475 |
+
(1/2, 3)
|
| 476 |
+
>>> perfect_power(Rational(-3, 2)**3)
|
| 477 |
+
(-3/2, 3)
|
| 478 |
+
|
| 479 |
+
Notes
|
| 480 |
+
=====
|
| 481 |
+
|
| 482 |
+
To know whether an integer is a perfect power of 2 use
|
| 483 |
+
|
| 484 |
+
>>> is2pow = lambda n: bool(n and not n & (n - 1))
|
| 485 |
+
>>> [(i, is2pow(i)) for i in range(5)]
|
| 486 |
+
[(0, False), (1, True), (2, True), (3, False), (4, True)]
|
| 487 |
+
|
| 488 |
+
It is not necessary to provide ``candidates``. When provided
|
| 489 |
+
it will be assumed that they are ints. The first one that is
|
| 490 |
+
larger than the computed maximum possible exponent will signal
|
| 491 |
+
failure for the routine.
|
| 492 |
+
|
| 493 |
+
>>> perfect_power(3**8, [9])
|
| 494 |
+
False
|
| 495 |
+
>>> perfect_power(3**8, [2, 4, 8])
|
| 496 |
+
(3, 8)
|
| 497 |
+
>>> perfect_power(3**8, [4, 8], big=False)
|
| 498 |
+
(9, 4)
|
| 499 |
+
|
| 500 |
+
See Also
|
| 501 |
+
========
|
| 502 |
+
sympy.core.intfunc.integer_nthroot
|
| 503 |
+
sympy.ntheory.primetest.is_square
|
| 504 |
+
"""
|
| 505 |
+
if isinstance(n, Rational) and not n.is_Integer:
|
| 506 |
+
p, q = n.as_numer_denom()
|
| 507 |
+
if p is S.One:
|
| 508 |
+
pp = perfect_power(q)
|
| 509 |
+
if pp:
|
| 510 |
+
pp = (n.func(1, pp[0]), pp[1])
|
| 511 |
+
else:
|
| 512 |
+
pp = perfect_power(p)
|
| 513 |
+
if pp:
|
| 514 |
+
num, e = pp
|
| 515 |
+
pq = perfect_power(q, [e])
|
| 516 |
+
if pq:
|
| 517 |
+
den, _ = pq
|
| 518 |
+
pp = n.func(num, den), e
|
| 519 |
+
return pp
|
| 520 |
+
|
| 521 |
+
n = as_int(n)
|
| 522 |
+
if n < 0:
|
| 523 |
+
pp = perfect_power(-n)
|
| 524 |
+
if pp:
|
| 525 |
+
b, e = pp
|
| 526 |
+
if e % 2:
|
| 527 |
+
return -b, e
|
| 528 |
+
return False
|
| 529 |
+
|
| 530 |
+
if candidates is None and big:
|
| 531 |
+
return _perfect_power(n)
|
| 532 |
+
|
| 533 |
+
if n <= 3:
|
| 534 |
+
# no unique exponent for 0, 1
|
| 535 |
+
# 2 and 3 have exponents of 1
|
| 536 |
+
return False
|
| 537 |
+
logn = math.log2(n)
|
| 538 |
+
max_possible = int(logn) + 2 # only check values less than this
|
| 539 |
+
not_square = n % 10 in [2, 3, 7, 8] # squares cannot end in 2, 3, 7, 8
|
| 540 |
+
min_possible = 2 + not_square
|
| 541 |
+
if not candidates:
|
| 542 |
+
candidates = primerange(min_possible, max_possible)
|
| 543 |
+
else:
|
| 544 |
+
candidates = sorted([i for i in candidates
|
| 545 |
+
if min_possible <= i < max_possible])
|
| 546 |
+
if n%2 == 0:
|
| 547 |
+
e = bit_scan1(n)
|
| 548 |
+
candidates = [i for i in candidates if e%i == 0]
|
| 549 |
+
if big:
|
| 550 |
+
candidates = reversed(candidates)
|
| 551 |
+
for e in candidates:
|
| 552 |
+
r, ok = iroot(n, e)
|
| 553 |
+
if ok:
|
| 554 |
+
return int(r), e
|
| 555 |
+
return False
|
| 556 |
+
|
| 557 |
+
def _factors():
|
| 558 |
+
rv = 2 + n % 2
|
| 559 |
+
while True:
|
| 560 |
+
yield rv
|
| 561 |
+
rv = nextprime(rv)
|
| 562 |
+
|
| 563 |
+
for fac, e in zip(_factors(), candidates):
|
| 564 |
+
# see if there is a factor present
|
| 565 |
+
if factor and n % fac == 0:
|
| 566 |
+
# find what the potential power is
|
| 567 |
+
e = remove(n, fac)[1]
|
| 568 |
+
# if it's a trivial power we are done
|
| 569 |
+
if e == 1:
|
| 570 |
+
return False
|
| 571 |
+
|
| 572 |
+
# maybe the e-th root of n is exact
|
| 573 |
+
r, exact = iroot(n, e)
|
| 574 |
+
if not exact:
|
| 575 |
+
# Having a factor, we know that e is the maximal
|
| 576 |
+
# possible value for a root of n.
|
| 577 |
+
# If n = fac**e*m can be written as a perfect
|
| 578 |
+
# power then see if m can be written as r**E where
|
| 579 |
+
# gcd(e, E) != 1 so n = (fac**(e//E)*r)**E
|
| 580 |
+
m = n//fac**e
|
| 581 |
+
rE = perfect_power(m, candidates=divisors(e, generator=True))
|
| 582 |
+
if not rE:
|
| 583 |
+
return False
|
| 584 |
+
else:
|
| 585 |
+
r, E = rE
|
| 586 |
+
r, e = fac**(e//E)*r, E
|
| 587 |
+
if not big:
|
| 588 |
+
e0 = primefactors(e)
|
| 589 |
+
if e0[0] != e:
|
| 590 |
+
r, e = r**(e//e0[0]), e0[0]
|
| 591 |
+
return int(r), e
|
| 592 |
+
|
| 593 |
+
# Weed out downright impossible candidates
|
| 594 |
+
if logn/e < 40:
|
| 595 |
+
b = 2.0**(logn/e)
|
| 596 |
+
if abs(int(b + 0.5) - b) > 0.01:
|
| 597 |
+
continue
|
| 598 |
+
|
| 599 |
+
# now see if the plausible e makes a perfect power
|
| 600 |
+
r, exact = iroot(n, e)
|
| 601 |
+
if exact:
|
| 602 |
+
if big:
|
| 603 |
+
m = perfect_power(r, big=big, factor=factor)
|
| 604 |
+
if m:
|
| 605 |
+
r, e = m[0], e*m[1]
|
| 606 |
+
return int(r), e
|
| 607 |
+
|
| 608 |
+
return False
|
| 609 |
+
|
| 610 |
+
|
| 611 |
+
def pollard_rho(n, s=2, a=1, retries=5, seed=1234, max_steps=None, F=None):
|
| 612 |
+
r"""
|
| 613 |
+
Use Pollard's rho method to try to extract a nontrivial factor
|
| 614 |
+
of ``n``. The returned factor may be a composite number. If no
|
| 615 |
+
factor is found, ``None`` is returned.
|
| 616 |
+
|
| 617 |
+
The algorithm generates pseudo-random values of x with a generator
|
| 618 |
+
function, replacing x with F(x). If F is not supplied then the
|
| 619 |
+
function x**2 + ``a`` is used. The first value supplied to F(x) is ``s``.
|
| 620 |
+
Upon failure (if ``retries`` is > 0) a new ``a`` and ``s`` will be
|
| 621 |
+
supplied; the ``a`` will be ignored if F was supplied.
|
| 622 |
+
|
| 623 |
+
The sequence of numbers generated by such functions generally have a
|
| 624 |
+
a lead-up to some number and then loop around back to that number and
|
| 625 |
+
begin to repeat the sequence, e.g. 1, 2, 3, 4, 5, 3, 4, 5 -- this leader
|
| 626 |
+
and loop look a bit like the Greek letter rho, and thus the name, 'rho'.
|
| 627 |
+
|
| 628 |
+
For a given function, very different leader-loop values can be obtained
|
| 629 |
+
so it is a good idea to allow for retries:
|
| 630 |
+
|
| 631 |
+
>>> from sympy.ntheory.generate import cycle_length
|
| 632 |
+
>>> n = 16843009
|
| 633 |
+
>>> F = lambda x:(2048*pow(x, 2, n) + 32767) % n
|
| 634 |
+
>>> for s in range(5):
|
| 635 |
+
... print('loop length = %4i; leader length = %3i' % next(cycle_length(F, s)))
|
| 636 |
+
...
|
| 637 |
+
loop length = 2489; leader length = 43
|
| 638 |
+
loop length = 78; leader length = 121
|
| 639 |
+
loop length = 1482; leader length = 100
|
| 640 |
+
loop length = 1482; leader length = 286
|
| 641 |
+
loop length = 1482; leader length = 101
|
| 642 |
+
|
| 643 |
+
Here is an explicit example where there is a three element leadup to
|
| 644 |
+
a sequence of 3 numbers (11, 14, 4) that then repeat:
|
| 645 |
+
|
| 646 |
+
>>> x=2
|
| 647 |
+
>>> for i in range(9):
|
| 648 |
+
... print(x)
|
| 649 |
+
... x=(x**2+12)%17
|
| 650 |
+
...
|
| 651 |
+
2
|
| 652 |
+
16
|
| 653 |
+
13
|
| 654 |
+
11
|
| 655 |
+
14
|
| 656 |
+
4
|
| 657 |
+
11
|
| 658 |
+
14
|
| 659 |
+
4
|
| 660 |
+
>>> next(cycle_length(lambda x: (x**2+12)%17, 2))
|
| 661 |
+
(3, 3)
|
| 662 |
+
>>> list(cycle_length(lambda x: (x**2+12)%17, 2, values=True))
|
| 663 |
+
[2, 16, 13, 11, 14, 4]
|
| 664 |
+
|
| 665 |
+
Instead of checking the differences of all generated values for a gcd
|
| 666 |
+
with n, only the kth and 2*kth numbers are checked, e.g. 1st and 2nd,
|
| 667 |
+
2nd and 4th, 3rd and 6th until it has been detected that the loop has been
|
| 668 |
+
traversed. Loops may be many thousands of steps long before rho finds a
|
| 669 |
+
factor or reports failure. If ``max_steps`` is specified, the iteration
|
| 670 |
+
is cancelled with a failure after the specified number of steps.
|
| 671 |
+
|
| 672 |
+
Examples
|
| 673 |
+
========
|
| 674 |
+
|
| 675 |
+
>>> from sympy import pollard_rho
|
| 676 |
+
>>> n=16843009
|
| 677 |
+
>>> F=lambda x:(2048*pow(x,2,n) + 32767) % n
|
| 678 |
+
>>> pollard_rho(n, F=F)
|
| 679 |
+
257
|
| 680 |
+
|
| 681 |
+
Use the default setting with a bad value of ``a`` and no retries:
|
| 682 |
+
|
| 683 |
+
>>> pollard_rho(n, a=n-2, retries=0)
|
| 684 |
+
|
| 685 |
+
If retries is > 0 then perhaps the problem will correct itself when
|
| 686 |
+
new values are generated for a:
|
| 687 |
+
|
| 688 |
+
>>> pollard_rho(n, a=n-2, retries=1)
|
| 689 |
+
257
|
| 690 |
+
|
| 691 |
+
References
|
| 692 |
+
==========
|
| 693 |
+
|
| 694 |
+
.. [1] Richard Crandall & Carl Pomerance (2005), "Prime Numbers:
|
| 695 |
+
A Computational Perspective", Springer, 2nd edition, 229-231
|
| 696 |
+
|
| 697 |
+
"""
|
| 698 |
+
n = int(n)
|
| 699 |
+
if n < 5:
|
| 700 |
+
raise ValueError('pollard_rho should receive n > 4')
|
| 701 |
+
randint = _randint(seed + retries)
|
| 702 |
+
V = s
|
| 703 |
+
for i in range(retries + 1):
|
| 704 |
+
U = V
|
| 705 |
+
if not F:
|
| 706 |
+
F = lambda x: (pow(x, 2, n) + a) % n
|
| 707 |
+
j = 0
|
| 708 |
+
while 1:
|
| 709 |
+
if max_steps and (j > max_steps):
|
| 710 |
+
break
|
| 711 |
+
j += 1
|
| 712 |
+
U = F(U)
|
| 713 |
+
V = F(F(V)) # V is 2x further along than U
|
| 714 |
+
g = gcd(U - V, n)
|
| 715 |
+
if g == 1:
|
| 716 |
+
continue
|
| 717 |
+
if g == n:
|
| 718 |
+
break
|
| 719 |
+
return int(g)
|
| 720 |
+
V = randint(0, n - 1)
|
| 721 |
+
a = randint(1, n - 3) # for x**2 + a, a%n should not be 0 or -2
|
| 722 |
+
F = None
|
| 723 |
+
return None
|
| 724 |
+
|
| 725 |
+
|
| 726 |
+
def pollard_pm1(n, B=10, a=2, retries=0, seed=1234):
|
| 727 |
+
"""
|
| 728 |
+
Use Pollard's p-1 method to try to extract a nontrivial factor
|
| 729 |
+
of ``n``. Either a divisor (perhaps composite) or ``None`` is returned.
|
| 730 |
+
|
| 731 |
+
The value of ``a`` is the base that is used in the test gcd(a**M - 1, n).
|
| 732 |
+
The default is 2. If ``retries`` > 0 then if no factor is found after the
|
| 733 |
+
first attempt, a new ``a`` will be generated randomly (using the ``seed``)
|
| 734 |
+
and the process repeated.
|
| 735 |
+
|
| 736 |
+
Note: the value of M is lcm(1..B) = reduce(ilcm, range(2, B + 1)).
|
| 737 |
+
|
| 738 |
+
A search is made for factors next to even numbers having a power smoothness
|
| 739 |
+
less than ``B``. Choosing a larger B increases the likelihood of finding a
|
| 740 |
+
larger factor but takes longer. Whether a factor of n is found or not
|
| 741 |
+
depends on ``a`` and the power smoothness of the even number just less than
|
| 742 |
+
the factor p (hence the name p - 1).
|
| 743 |
+
|
| 744 |
+
Although some discussion of what constitutes a good ``a`` some
|
| 745 |
+
descriptions are hard to interpret. At the modular.math site referenced
|
| 746 |
+
below it is stated that if gcd(a**M - 1, n) = N then a**M % q**r is 1
|
| 747 |
+
for every prime power divisor of N. But consider the following:
|
| 748 |
+
|
| 749 |
+
>>> from sympy.ntheory.factor_ import smoothness_p, pollard_pm1
|
| 750 |
+
>>> n=257*1009
|
| 751 |
+
>>> smoothness_p(n)
|
| 752 |
+
(-1, [(257, (1, 2, 256)), (1009, (1, 7, 16))])
|
| 753 |
+
|
| 754 |
+
So we should (and can) find a root with B=16:
|
| 755 |
+
|
| 756 |
+
>>> pollard_pm1(n, B=16, a=3)
|
| 757 |
+
1009
|
| 758 |
+
|
| 759 |
+
If we attempt to increase B to 256 we find that it does not work:
|
| 760 |
+
|
| 761 |
+
>>> pollard_pm1(n, B=256)
|
| 762 |
+
>>>
|
| 763 |
+
|
| 764 |
+
But if the value of ``a`` is changed we find that only multiples of
|
| 765 |
+
257 work, e.g.:
|
| 766 |
+
|
| 767 |
+
>>> pollard_pm1(n, B=256, a=257)
|
| 768 |
+
1009
|
| 769 |
+
|
| 770 |
+
Checking different ``a`` values shows that all the ones that did not
|
| 771 |
+
work had a gcd value not equal to ``n`` but equal to one of the
|
| 772 |
+
factors:
|
| 773 |
+
|
| 774 |
+
>>> from sympy import ilcm, igcd, factorint, Pow
|
| 775 |
+
>>> M = 1
|
| 776 |
+
>>> for i in range(2, 256):
|
| 777 |
+
... M = ilcm(M, i)
|
| 778 |
+
...
|
| 779 |
+
>>> set([igcd(pow(a, M, n) - 1, n) for a in range(2, 256) if
|
| 780 |
+
... igcd(pow(a, M, n) - 1, n) != n])
|
| 781 |
+
{1009}
|
| 782 |
+
|
| 783 |
+
But does aM % d for every divisor of n give 1?
|
| 784 |
+
|
| 785 |
+
>>> aM = pow(255, M, n)
|
| 786 |
+
>>> [(d, aM%Pow(*d.args)) for d in factorint(n, visual=True).args]
|
| 787 |
+
[(257**1, 1), (1009**1, 1)]
|
| 788 |
+
|
| 789 |
+
No, only one of them. So perhaps the principle is that a root will
|
| 790 |
+
be found for a given value of B provided that:
|
| 791 |
+
|
| 792 |
+
1) the power smoothness of the p - 1 value next to the root
|
| 793 |
+
does not exceed B
|
| 794 |
+
2) a**M % p != 1 for any of the divisors of n.
|
| 795 |
+
|
| 796 |
+
By trying more than one ``a`` it is possible that one of them
|
| 797 |
+
will yield a factor.
|
| 798 |
+
|
| 799 |
+
Examples
|
| 800 |
+
========
|
| 801 |
+
|
| 802 |
+
With the default smoothness bound, this number cannot be cracked:
|
| 803 |
+
|
| 804 |
+
>>> from sympy.ntheory import pollard_pm1
|
| 805 |
+
>>> pollard_pm1(21477639576571)
|
| 806 |
+
|
| 807 |
+
Increasing the smoothness bound helps:
|
| 808 |
+
|
| 809 |
+
>>> pollard_pm1(21477639576571, B=2000)
|
| 810 |
+
4410317
|
| 811 |
+
|
| 812 |
+
Looking at the smoothness of the factors of this number we find:
|
| 813 |
+
|
| 814 |
+
>>> from sympy.ntheory.factor_ import smoothness_p, factorint
|
| 815 |
+
>>> print(smoothness_p(21477639576571, visual=1))
|
| 816 |
+
p**i=4410317**1 has p-1 B=1787, B-pow=1787
|
| 817 |
+
p**i=4869863**1 has p-1 B=2434931, B-pow=2434931
|
| 818 |
+
|
| 819 |
+
The B and B-pow are the same for the p - 1 factorizations of the divisors
|
| 820 |
+
because those factorizations had a very large prime factor:
|
| 821 |
+
|
| 822 |
+
>>> factorint(4410317 - 1)
|
| 823 |
+
{2: 2, 617: 1, 1787: 1}
|
| 824 |
+
>>> factorint(4869863-1)
|
| 825 |
+
{2: 1, 2434931: 1}
|
| 826 |
+
|
| 827 |
+
Note that until B reaches the B-pow value of 1787, the number is not cracked;
|
| 828 |
+
|
| 829 |
+
>>> pollard_pm1(21477639576571, B=1786)
|
| 830 |
+
>>> pollard_pm1(21477639576571, B=1787)
|
| 831 |
+
4410317
|
| 832 |
+
|
| 833 |
+
The B value has to do with the factors of the number next to the divisor,
|
| 834 |
+
not the divisors themselves. A worst case scenario is that the number next
|
| 835 |
+
to the factor p has a large prime divisisor or is a perfect power. If these
|
| 836 |
+
conditions apply then the power-smoothness will be about p/2 or p. The more
|
| 837 |
+
realistic is that there will be a large prime factor next to p requiring
|
| 838 |
+
a B value on the order of p/2. Although primes may have been searched for
|
| 839 |
+
up to this level, the p/2 is a factor of p - 1, something that we do not
|
| 840 |
+
know. The modular.math reference below states that 15% of numbers in the
|
| 841 |
+
range of 10**15 to 15**15 + 10**4 are 10**6 power smooth so a B of 10**6
|
| 842 |
+
will fail 85% of the time in that range. From 10**8 to 10**8 + 10**3 the
|
| 843 |
+
percentages are nearly reversed...but in that range the simple trial
|
| 844 |
+
division is quite fast.
|
| 845 |
+
|
| 846 |
+
References
|
| 847 |
+
==========
|
| 848 |
+
|
| 849 |
+
.. [1] Richard Crandall & Carl Pomerance (2005), "Prime Numbers:
|
| 850 |
+
A Computational Perspective", Springer, 2nd edition, 236-238
|
| 851 |
+
.. [2] https://web.archive.org/web/20150716201437/http://modular.math.washington.edu/edu/2007/spring/ent/ent-html/node81.html
|
| 852 |
+
.. [3] https://www.cs.toronto.edu/~yuvalf/Factorization.pdf
|
| 853 |
+
"""
|
| 854 |
+
|
| 855 |
+
n = int(n)
|
| 856 |
+
if n < 4 or B < 3:
|
| 857 |
+
raise ValueError('pollard_pm1 should receive n > 3 and B > 2')
|
| 858 |
+
randint = _randint(seed + B)
|
| 859 |
+
|
| 860 |
+
# computing a**lcm(1,2,3,..B) % n for B > 2
|
| 861 |
+
# it looks weird, but it's right: primes run [2, B]
|
| 862 |
+
# and the answer's not right until the loop is done.
|
| 863 |
+
for i in range(retries + 1):
|
| 864 |
+
aM = a
|
| 865 |
+
for p in sieve.primerange(2, B + 1):
|
| 866 |
+
e = int(math.log(B, p))
|
| 867 |
+
aM = pow(aM, pow(p, e), n)
|
| 868 |
+
g = gcd(aM - 1, n)
|
| 869 |
+
if 1 < g < n:
|
| 870 |
+
return int(g)
|
| 871 |
+
|
| 872 |
+
# get a new a:
|
| 873 |
+
# since the exponent, lcm(1..B), is even, if we allow 'a' to be 'n-1'
|
| 874 |
+
# then (n - 1)**even % n will be 1 which will give a g of 0 and 1 will
|
| 875 |
+
# give a zero, too, so we set the range as [2, n-2]. Some references
|
| 876 |
+
# say 'a' should be coprime to n, but either will detect factors.
|
| 877 |
+
a = randint(2, n - 2)
|
| 878 |
+
|
| 879 |
+
|
| 880 |
+
def _trial(factors, n, candidates, verbose=False):
|
| 881 |
+
"""
|
| 882 |
+
Helper function for integer factorization. Trial factors ``n`
|
| 883 |
+
against all integers given in the sequence ``candidates``
|
| 884 |
+
and updates the dict ``factors`` in-place. Returns the reduced
|
| 885 |
+
value of ``n`` and a flag indicating whether any factors were found.
|
| 886 |
+
"""
|
| 887 |
+
if verbose:
|
| 888 |
+
factors0 = list(factors.keys())
|
| 889 |
+
nfactors = len(factors)
|
| 890 |
+
for d in candidates:
|
| 891 |
+
if n % d == 0:
|
| 892 |
+
n, m = remove(n // d, d)
|
| 893 |
+
factors[d] = m + 1
|
| 894 |
+
if verbose:
|
| 895 |
+
for k in sorted(set(factors).difference(set(factors0))):
|
| 896 |
+
print(factor_msg % (k, factors[k]))
|
| 897 |
+
return int(n), len(factors) != nfactors
|
| 898 |
+
|
| 899 |
+
|
| 900 |
+
def _check_termination(factors, n, limit, use_trial, use_rho, use_pm1,
|
| 901 |
+
verbose, next_p):
|
| 902 |
+
"""
|
| 903 |
+
Helper function for integer factorization. Checks if ``n``
|
| 904 |
+
is a prime or a perfect power, and in those cases updates the factorization.
|
| 905 |
+
"""
|
| 906 |
+
if verbose:
|
| 907 |
+
print('Check for termination')
|
| 908 |
+
if n == 1:
|
| 909 |
+
if verbose:
|
| 910 |
+
print(complete_msg)
|
| 911 |
+
return True
|
| 912 |
+
if n < next_p**2 or isprime(n):
|
| 913 |
+
factors[int(n)] = 1
|
| 914 |
+
if verbose:
|
| 915 |
+
print(complete_msg)
|
| 916 |
+
return True
|
| 917 |
+
|
| 918 |
+
# since we've already been factoring there is no need to do
|
| 919 |
+
# simultaneous factoring with the power check
|
| 920 |
+
p = _perfect_power(n, next_p)
|
| 921 |
+
if not p:
|
| 922 |
+
return False
|
| 923 |
+
base, exp = p
|
| 924 |
+
if base < next_p**2 or isprime(base):
|
| 925 |
+
factors[base] = exp
|
| 926 |
+
else:
|
| 927 |
+
facs = factorint(base, limit, use_trial, use_rho, use_pm1,
|
| 928 |
+
verbose=False)
|
| 929 |
+
for b, e in facs.items():
|
| 930 |
+
if verbose:
|
| 931 |
+
print(factor_msg % (b, e))
|
| 932 |
+
# int() can be removed when https://github.com/flintlib/python-flint/issues/92 is resolved
|
| 933 |
+
factors[b] = int(exp*e)
|
| 934 |
+
if verbose:
|
| 935 |
+
print(complete_msg)
|
| 936 |
+
return True
|
| 937 |
+
|
| 938 |
+
|
| 939 |
+
trial_int_msg = "Trial division with ints [%i ... %i] and fail_max=%i"
|
| 940 |
+
trial_msg = "Trial division with primes [%i ... %i]"
|
| 941 |
+
rho_msg = "Pollard's rho with retries %i, max_steps %i and seed %i"
|
| 942 |
+
pm1_msg = "Pollard's p-1 with smoothness bound %i and seed %i"
|
| 943 |
+
ecm_msg = "Elliptic Curve with B1 bound %i, B2 bound %i, num_curves %i"
|
| 944 |
+
factor_msg = '\t%i ** %i'
|
| 945 |
+
fermat_msg = 'Close factors satisying Fermat condition found.'
|
| 946 |
+
complete_msg = 'Factorization is complete.'
|
| 947 |
+
|
| 948 |
+
|
| 949 |
+
def _factorint_small(factors, n, limit, fail_max, next_p=2):
|
| 950 |
+
"""
|
| 951 |
+
Return the value of n and either a 0 (indicating that factorization up
|
| 952 |
+
to the limit was complete) or else the next near-prime that would have
|
| 953 |
+
been tested.
|
| 954 |
+
|
| 955 |
+
Factoring stops if there are fail_max unsuccessful tests in a row.
|
| 956 |
+
|
| 957 |
+
If factors of n were found they will be in the factors dictionary as
|
| 958 |
+
{factor: multiplicity} and the returned value of n will have had those
|
| 959 |
+
factors removed. The factors dictionary is modified in-place.
|
| 960 |
+
|
| 961 |
+
"""
|
| 962 |
+
|
| 963 |
+
def done(n, d):
|
| 964 |
+
"""return n, d if the sqrt(n) was not reached yet, else
|
| 965 |
+
n, 0 indicating that factoring is done.
|
| 966 |
+
"""
|
| 967 |
+
if d*d <= n:
|
| 968 |
+
return n, d
|
| 969 |
+
return n, 0
|
| 970 |
+
|
| 971 |
+
limit2 = limit**2
|
| 972 |
+
threshold2 = min(n, limit2)
|
| 973 |
+
|
| 974 |
+
if next_p < 3:
|
| 975 |
+
if not n & 1:
|
| 976 |
+
m = bit_scan1(n)
|
| 977 |
+
factors[2] = m
|
| 978 |
+
n >>= m
|
| 979 |
+
threshold2 = min(n, limit2)
|
| 980 |
+
next_p = 3
|
| 981 |
+
if threshold2 < 9: # next_p**2 = 9
|
| 982 |
+
return done(n, next_p)
|
| 983 |
+
|
| 984 |
+
if next_p < 5:
|
| 985 |
+
if not n % 3:
|
| 986 |
+
n //= 3
|
| 987 |
+
m = 1
|
| 988 |
+
while not n % 3:
|
| 989 |
+
n //= 3
|
| 990 |
+
m += 1
|
| 991 |
+
if m == 20:
|
| 992 |
+
n, mm = remove(n, 3)
|
| 993 |
+
m += mm
|
| 994 |
+
break
|
| 995 |
+
factors[3] = m
|
| 996 |
+
threshold2 = min(n, limit2)
|
| 997 |
+
next_p = 5
|
| 998 |
+
if threshold2 < 25: # next_p**2 = 25
|
| 999 |
+
return done(n, next_p)
|
| 1000 |
+
|
| 1001 |
+
# Because of the order of checks, starting from `min_p = 6k+5`,
|
| 1002 |
+
# useless checks are caused.
|
| 1003 |
+
# We want to calculate
|
| 1004 |
+
# next_p += [-1, -2, 3, 2, 1, 0][next_p % 6]
|
| 1005 |
+
p6 = next_p % 6
|
| 1006 |
+
next_p += (-1 if p6 < 2 else 5) - p6
|
| 1007 |
+
|
| 1008 |
+
fails = 0
|
| 1009 |
+
while fails < fail_max:
|
| 1010 |
+
# next_p % 6 == 5
|
| 1011 |
+
if n % next_p:
|
| 1012 |
+
fails += 1
|
| 1013 |
+
else:
|
| 1014 |
+
n //= next_p
|
| 1015 |
+
m = 1
|
| 1016 |
+
while not n % next_p:
|
| 1017 |
+
n //= next_p
|
| 1018 |
+
m += 1
|
| 1019 |
+
if m == 20:
|
| 1020 |
+
n, mm = remove(n, next_p)
|
| 1021 |
+
m += mm
|
| 1022 |
+
break
|
| 1023 |
+
factors[next_p] = m
|
| 1024 |
+
fails = 0
|
| 1025 |
+
threshold2 = min(n, limit2)
|
| 1026 |
+
next_p += 2
|
| 1027 |
+
if threshold2 < next_p**2:
|
| 1028 |
+
return done(n, next_p)
|
| 1029 |
+
|
| 1030 |
+
# next_p % 6 == 1
|
| 1031 |
+
if n % next_p:
|
| 1032 |
+
fails += 1
|
| 1033 |
+
else:
|
| 1034 |
+
n //= next_p
|
| 1035 |
+
m = 1
|
| 1036 |
+
while not n % next_p:
|
| 1037 |
+
n //= next_p
|
| 1038 |
+
m += 1
|
| 1039 |
+
if m == 20:
|
| 1040 |
+
n, mm = remove(n, next_p)
|
| 1041 |
+
m += mm
|
| 1042 |
+
break
|
| 1043 |
+
factors[next_p] = m
|
| 1044 |
+
fails = 0
|
| 1045 |
+
threshold2 = min(n, limit2)
|
| 1046 |
+
next_p += 4
|
| 1047 |
+
if threshold2 < next_p**2:
|
| 1048 |
+
return done(n, next_p)
|
| 1049 |
+
return done(n, next_p)
|
| 1050 |
+
|
| 1051 |
+
|
| 1052 |
+
def factorint(n, limit=None, use_trial=True, use_rho=True, use_pm1=True,
|
| 1053 |
+
use_ecm=True, verbose=False, visual=None, multiple=False):
|
| 1054 |
+
r"""
|
| 1055 |
+
Given a positive integer ``n``, ``factorint(n)`` returns a dict containing
|
| 1056 |
+
the prime factors of ``n`` as keys and their respective multiplicities
|
| 1057 |
+
as values. For example:
|
| 1058 |
+
|
| 1059 |
+
>>> from sympy.ntheory import factorint
|
| 1060 |
+
>>> factorint(2000) # 2000 = (2**4) * (5**3)
|
| 1061 |
+
{2: 4, 5: 3}
|
| 1062 |
+
>>> factorint(65537) # This number is prime
|
| 1063 |
+
{65537: 1}
|
| 1064 |
+
|
| 1065 |
+
For input less than 2, factorint behaves as follows:
|
| 1066 |
+
|
| 1067 |
+
- ``factorint(1)`` returns the empty factorization, ``{}``
|
| 1068 |
+
- ``factorint(0)`` returns ``{0:1}``
|
| 1069 |
+
- ``factorint(-n)`` adds ``-1:1`` to the factors and then factors ``n``
|
| 1070 |
+
|
| 1071 |
+
Partial Factorization:
|
| 1072 |
+
|
| 1073 |
+
If ``limit`` (> 3) is specified, the search is stopped after performing
|
| 1074 |
+
trial division up to (and including) the limit (or taking a
|
| 1075 |
+
corresponding number of rho/p-1 steps). This is useful if one has
|
| 1076 |
+
a large number and only is interested in finding small factors (if
|
| 1077 |
+
any). Note that setting a limit does not prevent larger factors
|
| 1078 |
+
from being found early; it simply means that the largest factor may
|
| 1079 |
+
be composite. Since checking for perfect power is relatively cheap, it is
|
| 1080 |
+
done regardless of the limit setting.
|
| 1081 |
+
|
| 1082 |
+
This number, for example, has two small factors and a huge
|
| 1083 |
+
semi-prime factor that cannot be reduced easily:
|
| 1084 |
+
|
| 1085 |
+
>>> from sympy.ntheory import isprime
|
| 1086 |
+
>>> a = 1407633717262338957430697921446883
|
| 1087 |
+
>>> f = factorint(a, limit=10000)
|
| 1088 |
+
>>> f == {991: 1, int(202916782076162456022877024859): 1, 7: 1}
|
| 1089 |
+
True
|
| 1090 |
+
>>> isprime(max(f))
|
| 1091 |
+
False
|
| 1092 |
+
|
| 1093 |
+
This number has a small factor and a residual perfect power whose
|
| 1094 |
+
base is greater than the limit:
|
| 1095 |
+
|
| 1096 |
+
>>> factorint(3*101**7, limit=5)
|
| 1097 |
+
{3: 1, 101: 7}
|
| 1098 |
+
|
| 1099 |
+
List of Factors:
|
| 1100 |
+
|
| 1101 |
+
If ``multiple`` is set to ``True`` then a list containing the
|
| 1102 |
+
prime factors including multiplicities is returned.
|
| 1103 |
+
|
| 1104 |
+
>>> factorint(24, multiple=True)
|
| 1105 |
+
[2, 2, 2, 3]
|
| 1106 |
+
|
| 1107 |
+
Visual Factorization:
|
| 1108 |
+
|
| 1109 |
+
If ``visual`` is set to ``True``, then it will return a visual
|
| 1110 |
+
factorization of the integer. For example:
|
| 1111 |
+
|
| 1112 |
+
>>> from sympy import pprint
|
| 1113 |
+
>>> pprint(factorint(4200, visual=True))
|
| 1114 |
+
3 1 2 1
|
| 1115 |
+
2 *3 *5 *7
|
| 1116 |
+
|
| 1117 |
+
Note that this is achieved by using the evaluate=False flag in Mul
|
| 1118 |
+
and Pow. If you do other manipulations with an expression where
|
| 1119 |
+
evaluate=False, it may evaluate. Therefore, you should use the
|
| 1120 |
+
visual option only for visualization, and use the normal dictionary
|
| 1121 |
+
returned by visual=False if you want to perform operations on the
|
| 1122 |
+
factors.
|
| 1123 |
+
|
| 1124 |
+
You can easily switch between the two forms by sending them back to
|
| 1125 |
+
factorint:
|
| 1126 |
+
|
| 1127 |
+
>>> from sympy import Mul
|
| 1128 |
+
>>> regular = factorint(1764); regular
|
| 1129 |
+
{2: 2, 3: 2, 7: 2}
|
| 1130 |
+
>>> pprint(factorint(regular))
|
| 1131 |
+
2 2 2
|
| 1132 |
+
2 *3 *7
|
| 1133 |
+
|
| 1134 |
+
>>> visual = factorint(1764, visual=True); pprint(visual)
|
| 1135 |
+
2 2 2
|
| 1136 |
+
2 *3 *7
|
| 1137 |
+
>>> print(factorint(visual))
|
| 1138 |
+
{2: 2, 3: 2, 7: 2}
|
| 1139 |
+
|
| 1140 |
+
If you want to send a number to be factored in a partially factored form
|
| 1141 |
+
you can do so with a dictionary or unevaluated expression:
|
| 1142 |
+
|
| 1143 |
+
>>> factorint(factorint({4: 2, 12: 3})) # twice to toggle to dict form
|
| 1144 |
+
{2: 10, 3: 3}
|
| 1145 |
+
>>> factorint(Mul(4, 12, evaluate=False))
|
| 1146 |
+
{2: 4, 3: 1}
|
| 1147 |
+
|
| 1148 |
+
The table of the output logic is:
|
| 1149 |
+
|
| 1150 |
+
====== ====== ======= =======
|
| 1151 |
+
Visual
|
| 1152 |
+
------ ----------------------
|
| 1153 |
+
Input True False other
|
| 1154 |
+
====== ====== ======= =======
|
| 1155 |
+
dict mul dict mul
|
| 1156 |
+
n mul dict dict
|
| 1157 |
+
mul mul dict dict
|
| 1158 |
+
====== ====== ======= =======
|
| 1159 |
+
|
| 1160 |
+
Notes
|
| 1161 |
+
=====
|
| 1162 |
+
|
| 1163 |
+
Algorithm:
|
| 1164 |
+
|
| 1165 |
+
The function switches between multiple algorithms. Trial division
|
| 1166 |
+
quickly finds small factors (of the order 1-5 digits), and finds
|
| 1167 |
+
all large factors if given enough time. The Pollard rho and p-1
|
| 1168 |
+
algorithms are used to find large factors ahead of time; they
|
| 1169 |
+
will often find factors of the order of 10 digits within a few
|
| 1170 |
+
seconds:
|
| 1171 |
+
|
| 1172 |
+
>>> factors = factorint(12345678910111213141516)
|
| 1173 |
+
>>> for base, exp in sorted(factors.items()):
|
| 1174 |
+
... print('%s %s' % (base, exp))
|
| 1175 |
+
...
|
| 1176 |
+
2 2
|
| 1177 |
+
2507191691 1
|
| 1178 |
+
1231026625769 1
|
| 1179 |
+
|
| 1180 |
+
Any of these methods can optionally be disabled with the following
|
| 1181 |
+
boolean parameters:
|
| 1182 |
+
|
| 1183 |
+
- ``use_trial``: Toggle use of trial division
|
| 1184 |
+
- ``use_rho``: Toggle use of Pollard's rho method
|
| 1185 |
+
- ``use_pm1``: Toggle use of Pollard's p-1 method
|
| 1186 |
+
|
| 1187 |
+
``factorint`` also periodically checks if the remaining part is
|
| 1188 |
+
a prime number or a perfect power, and in those cases stops.
|
| 1189 |
+
|
| 1190 |
+
For unevaluated factorial, it uses Legendre's formula(theorem).
|
| 1191 |
+
|
| 1192 |
+
|
| 1193 |
+
If ``verbose`` is set to ``True``, detailed progress is printed.
|
| 1194 |
+
|
| 1195 |
+
See Also
|
| 1196 |
+
========
|
| 1197 |
+
|
| 1198 |
+
smoothness, smoothness_p, divisors
|
| 1199 |
+
|
| 1200 |
+
"""
|
| 1201 |
+
if isinstance(n, Dict):
|
| 1202 |
+
n = dict(n)
|
| 1203 |
+
if multiple:
|
| 1204 |
+
fac = factorint(n, limit=limit, use_trial=use_trial,
|
| 1205 |
+
use_rho=use_rho, use_pm1=use_pm1,
|
| 1206 |
+
verbose=verbose, visual=False, multiple=False)
|
| 1207 |
+
factorlist = sum(([p] * fac[p] if fac[p] > 0 else [S.One/p]*(-fac[p])
|
| 1208 |
+
for p in sorted(fac)), [])
|
| 1209 |
+
return factorlist
|
| 1210 |
+
|
| 1211 |
+
factordict = {}
|
| 1212 |
+
if visual and not isinstance(n, (Mul, dict)):
|
| 1213 |
+
factordict = factorint(n, limit=limit, use_trial=use_trial,
|
| 1214 |
+
use_rho=use_rho, use_pm1=use_pm1,
|
| 1215 |
+
verbose=verbose, visual=False)
|
| 1216 |
+
elif isinstance(n, Mul):
|
| 1217 |
+
factordict = {int(k): int(v) for k, v in
|
| 1218 |
+
n.as_powers_dict().items()}
|
| 1219 |
+
elif isinstance(n, dict):
|
| 1220 |
+
factordict = n
|
| 1221 |
+
if factordict and isinstance(n, (Mul, dict)):
|
| 1222 |
+
# check it
|
| 1223 |
+
for key in list(factordict.keys()):
|
| 1224 |
+
if isprime(key):
|
| 1225 |
+
continue
|
| 1226 |
+
e = factordict.pop(key)
|
| 1227 |
+
d = factorint(key, limit=limit, use_trial=use_trial, use_rho=use_rho,
|
| 1228 |
+
use_pm1=use_pm1, verbose=verbose, visual=False)
|
| 1229 |
+
for k, v in d.items():
|
| 1230 |
+
if k in factordict:
|
| 1231 |
+
factordict[k] += v*e
|
| 1232 |
+
else:
|
| 1233 |
+
factordict[k] = v*e
|
| 1234 |
+
if visual or (type(n) is dict and
|
| 1235 |
+
visual is not True and
|
| 1236 |
+
visual is not False):
|
| 1237 |
+
if factordict == {}:
|
| 1238 |
+
return S.One
|
| 1239 |
+
if -1 in factordict:
|
| 1240 |
+
factordict.pop(-1)
|
| 1241 |
+
args = [S.NegativeOne]
|
| 1242 |
+
else:
|
| 1243 |
+
args = []
|
| 1244 |
+
args.extend([Pow(*i, evaluate=False)
|
| 1245 |
+
for i in sorted(factordict.items())])
|
| 1246 |
+
return Mul(*args, evaluate=False)
|
| 1247 |
+
elif isinstance(n, (dict, Mul)):
|
| 1248 |
+
return factordict
|
| 1249 |
+
|
| 1250 |
+
assert use_trial or use_rho or use_pm1 or use_ecm
|
| 1251 |
+
|
| 1252 |
+
from sympy.functions.combinatorial.factorials import factorial
|
| 1253 |
+
if isinstance(n, factorial):
|
| 1254 |
+
x = as_int(n.args[0])
|
| 1255 |
+
if x >= 20:
|
| 1256 |
+
factors = {}
|
| 1257 |
+
m = 2 # to initialize the if condition below
|
| 1258 |
+
for p in sieve.primerange(2, x + 1):
|
| 1259 |
+
if m > 1:
|
| 1260 |
+
m, q = 0, x // p
|
| 1261 |
+
while q != 0:
|
| 1262 |
+
m += q
|
| 1263 |
+
q //= p
|
| 1264 |
+
factors[p] = m
|
| 1265 |
+
if factors and verbose:
|
| 1266 |
+
for k in sorted(factors):
|
| 1267 |
+
print(factor_msg % (k, factors[k]))
|
| 1268 |
+
if verbose:
|
| 1269 |
+
print(complete_msg)
|
| 1270 |
+
return factors
|
| 1271 |
+
else:
|
| 1272 |
+
# if n < 20!, direct computation is faster
|
| 1273 |
+
# since it uses a lookup table
|
| 1274 |
+
n = n.func(x)
|
| 1275 |
+
|
| 1276 |
+
n = as_int(n)
|
| 1277 |
+
if limit:
|
| 1278 |
+
limit = int(limit)
|
| 1279 |
+
use_ecm = False
|
| 1280 |
+
|
| 1281 |
+
# special cases
|
| 1282 |
+
if n < 0:
|
| 1283 |
+
factors = factorint(
|
| 1284 |
+
-n, limit=limit, use_trial=use_trial, use_rho=use_rho,
|
| 1285 |
+
use_pm1=use_pm1, verbose=verbose, visual=False)
|
| 1286 |
+
factors[-1] = 1
|
| 1287 |
+
return factors
|
| 1288 |
+
|
| 1289 |
+
if limit and limit < 2:
|
| 1290 |
+
if n == 1:
|
| 1291 |
+
return {}
|
| 1292 |
+
return {n: 1}
|
| 1293 |
+
elif n < 10:
|
| 1294 |
+
# doing this we are assured of getting a limit > 2
|
| 1295 |
+
# when we have to compute it later
|
| 1296 |
+
return [{0: 1}, {}, {2: 1}, {3: 1}, {2: 2}, {5: 1},
|
| 1297 |
+
{2: 1, 3: 1}, {7: 1}, {2: 3}, {3: 2}][n]
|
| 1298 |
+
|
| 1299 |
+
factors = {}
|
| 1300 |
+
|
| 1301 |
+
# do simplistic factorization
|
| 1302 |
+
if verbose:
|
| 1303 |
+
sn = str(n)
|
| 1304 |
+
if len(sn) > 50:
|
| 1305 |
+
print('Factoring %s' % sn[:5] + \
|
| 1306 |
+
'..(%i other digits)..' % (len(sn) - 10) + sn[-5:])
|
| 1307 |
+
else:
|
| 1308 |
+
print('Factoring', n)
|
| 1309 |
+
|
| 1310 |
+
# this is the preliminary factorization for small factors
|
| 1311 |
+
# We want to guarantee that there are no small prime factors,
|
| 1312 |
+
# so we run even if `use_trial` is False.
|
| 1313 |
+
small = 2**15
|
| 1314 |
+
fail_max = 600
|
| 1315 |
+
small = min(small, limit or small)
|
| 1316 |
+
if verbose:
|
| 1317 |
+
print(trial_int_msg % (2, small, fail_max))
|
| 1318 |
+
n, next_p = _factorint_small(factors, n, small, fail_max)
|
| 1319 |
+
if factors and verbose:
|
| 1320 |
+
for k in sorted(factors):
|
| 1321 |
+
print(factor_msg % (k, factors[k]))
|
| 1322 |
+
if next_p == 0:
|
| 1323 |
+
if n > 1:
|
| 1324 |
+
factors[int(n)] = 1
|
| 1325 |
+
if verbose:
|
| 1326 |
+
print(complete_msg)
|
| 1327 |
+
return factors
|
| 1328 |
+
# first check if the simplistic run didn't finish
|
| 1329 |
+
# because of the limit and check for a perfect
|
| 1330 |
+
# power before exiting
|
| 1331 |
+
if limit and next_p > limit:
|
| 1332 |
+
if verbose:
|
| 1333 |
+
print('Exceeded limit:', limit)
|
| 1334 |
+
if _check_termination(factors, n, limit, use_trial,
|
| 1335 |
+
use_rho, use_pm1, verbose, next_p):
|
| 1336 |
+
return factors
|
| 1337 |
+
if n > 1:
|
| 1338 |
+
factors[int(n)] = 1
|
| 1339 |
+
return factors
|
| 1340 |
+
if _check_termination(factors, n, limit, use_trial,
|
| 1341 |
+
use_rho, use_pm1, verbose, next_p):
|
| 1342 |
+
return factors
|
| 1343 |
+
|
| 1344 |
+
# continue with more advanced factorization methods
|
| 1345 |
+
# ...do a Fermat test since it's so easy and we need the
|
| 1346 |
+
# square root anyway. Finding 2 factors is easy if they are
|
| 1347 |
+
# "close enough." This is the big root equivalent of dividing by
|
| 1348 |
+
# 2, 3, 5.
|
| 1349 |
+
sqrt_n = isqrt(n)
|
| 1350 |
+
a = sqrt_n + 1
|
| 1351 |
+
# If `n % 4 == 1`, `a` must be odd for `a**2 - n` to be a square number.
|
| 1352 |
+
if (n % 4 == 1) ^ (a & 1):
|
| 1353 |
+
a += 1
|
| 1354 |
+
a2 = a**2
|
| 1355 |
+
b2 = a2 - n
|
| 1356 |
+
for _ in range(3):
|
| 1357 |
+
b, fermat = sqrtrem(b2)
|
| 1358 |
+
if not fermat:
|
| 1359 |
+
if verbose:
|
| 1360 |
+
print(fermat_msg)
|
| 1361 |
+
for r in [a - b, a + b]:
|
| 1362 |
+
facs = factorint(r, limit=limit, use_trial=use_trial,
|
| 1363 |
+
use_rho=use_rho, use_pm1=use_pm1,
|
| 1364 |
+
verbose=verbose)
|
| 1365 |
+
for k, v in facs.items():
|
| 1366 |
+
factors[k] = factors.get(k, 0) + v
|
| 1367 |
+
if verbose:
|
| 1368 |
+
print(complete_msg)
|
| 1369 |
+
return factors
|
| 1370 |
+
b2 += (a + 1) << 2 # equiv to (a + 2)**2 - n
|
| 1371 |
+
a += 2
|
| 1372 |
+
|
| 1373 |
+
# these are the limits for trial division which will
|
| 1374 |
+
# be attempted in parallel with pollard methods
|
| 1375 |
+
low, high = next_p, 2*next_p
|
| 1376 |
+
|
| 1377 |
+
# add 1 to make sure limit is reached in primerange calls
|
| 1378 |
+
_limit = (limit or sqrt_n) + 1
|
| 1379 |
+
iteration = 0
|
| 1380 |
+
while 1:
|
| 1381 |
+
high_ = min(high, _limit)
|
| 1382 |
+
|
| 1383 |
+
# Trial division
|
| 1384 |
+
if use_trial:
|
| 1385 |
+
if verbose:
|
| 1386 |
+
print(trial_msg % (low, high_))
|
| 1387 |
+
ps = sieve.primerange(low, high_)
|
| 1388 |
+
n, found_trial = _trial(factors, n, ps, verbose)
|
| 1389 |
+
next_p = high_
|
| 1390 |
+
if found_trial and _check_termination(factors, n, limit, use_trial,
|
| 1391 |
+
use_rho, use_pm1, verbose, next_p):
|
| 1392 |
+
return factors
|
| 1393 |
+
else:
|
| 1394 |
+
found_trial = False
|
| 1395 |
+
|
| 1396 |
+
if high > _limit:
|
| 1397 |
+
if verbose:
|
| 1398 |
+
print('Exceeded limit:', _limit)
|
| 1399 |
+
if n > 1:
|
| 1400 |
+
factors[int(n)] = 1
|
| 1401 |
+
if verbose:
|
| 1402 |
+
print(complete_msg)
|
| 1403 |
+
return factors
|
| 1404 |
+
|
| 1405 |
+
# Only used advanced methods when no small factors were found
|
| 1406 |
+
if not found_trial:
|
| 1407 |
+
# Pollard p-1
|
| 1408 |
+
if use_pm1:
|
| 1409 |
+
if verbose:
|
| 1410 |
+
print(pm1_msg % (low, high_))
|
| 1411 |
+
c = pollard_pm1(n, B=low, seed=high_)
|
| 1412 |
+
if c:
|
| 1413 |
+
if c < next_p**2 or isprime(c):
|
| 1414 |
+
ps = [c]
|
| 1415 |
+
else:
|
| 1416 |
+
ps = factorint(c, limit=limit,
|
| 1417 |
+
use_trial=use_trial,
|
| 1418 |
+
use_rho=use_rho,
|
| 1419 |
+
use_pm1=use_pm1,
|
| 1420 |
+
use_ecm=use_ecm,
|
| 1421 |
+
verbose=verbose)
|
| 1422 |
+
n, _ = _trial(factors, n, ps, verbose=False)
|
| 1423 |
+
if _check_termination(factors, n, limit, use_trial,
|
| 1424 |
+
use_rho, use_pm1, verbose, next_p):
|
| 1425 |
+
return factors
|
| 1426 |
+
|
| 1427 |
+
# Pollard rho
|
| 1428 |
+
if use_rho:
|
| 1429 |
+
if verbose:
|
| 1430 |
+
print(rho_msg % (1, low, high_))
|
| 1431 |
+
c = pollard_rho(n, retries=1, max_steps=low, seed=high_)
|
| 1432 |
+
if c:
|
| 1433 |
+
if c < next_p**2 or isprime(c):
|
| 1434 |
+
ps = [c]
|
| 1435 |
+
else:
|
| 1436 |
+
ps = factorint(c, limit=limit,
|
| 1437 |
+
use_trial=use_trial,
|
| 1438 |
+
use_rho=use_rho,
|
| 1439 |
+
use_pm1=use_pm1,
|
| 1440 |
+
use_ecm=use_ecm,
|
| 1441 |
+
verbose=verbose)
|
| 1442 |
+
n, _ = _trial(factors, n, ps, verbose=False)
|
| 1443 |
+
if _check_termination(factors, n, limit, use_trial,
|
| 1444 |
+
use_rho, use_pm1, verbose, next_p):
|
| 1445 |
+
return factors
|
| 1446 |
+
# Use subexponential algorithms if use_ecm
|
| 1447 |
+
# Use pollard algorithms for finding small factors for 3 iterations
|
| 1448 |
+
# if after small factors the number of digits of n >= 25 then use ecm
|
| 1449 |
+
iteration += 1
|
| 1450 |
+
if use_ecm and iteration >= 3 and num_digits(n) >= 24:
|
| 1451 |
+
break
|
| 1452 |
+
low, high = high, high*2
|
| 1453 |
+
|
| 1454 |
+
B1 = 10000
|
| 1455 |
+
B2 = 100*B1
|
| 1456 |
+
num_curves = 50
|
| 1457 |
+
while(1):
|
| 1458 |
+
if verbose:
|
| 1459 |
+
print(ecm_msg % (B1, B2, num_curves))
|
| 1460 |
+
factor = _ecm_one_factor(n, B1, B2, num_curves, seed=B1)
|
| 1461 |
+
if factor:
|
| 1462 |
+
if factor < next_p**2 or isprime(factor):
|
| 1463 |
+
ps = [factor]
|
| 1464 |
+
else:
|
| 1465 |
+
ps = factorint(factor, limit=limit,
|
| 1466 |
+
use_trial=use_trial,
|
| 1467 |
+
use_rho=use_rho,
|
| 1468 |
+
use_pm1=use_pm1,
|
| 1469 |
+
use_ecm=use_ecm,
|
| 1470 |
+
verbose=verbose)
|
| 1471 |
+
n, _ = _trial(factors, n, ps, verbose=False)
|
| 1472 |
+
if _check_termination(factors, n, limit, use_trial,
|
| 1473 |
+
use_rho, use_pm1, verbose, next_p):
|
| 1474 |
+
return factors
|
| 1475 |
+
B1 *= 5
|
| 1476 |
+
B2 = 100*B1
|
| 1477 |
+
num_curves *= 4
|
| 1478 |
+
|
| 1479 |
+
|
| 1480 |
+
def factorrat(rat, limit=None, use_trial=True, use_rho=True, use_pm1=True,
|
| 1481 |
+
verbose=False, visual=None, multiple=False):
|
| 1482 |
+
r"""
|
| 1483 |
+
Given a Rational ``r``, ``factorrat(r)`` returns a dict containing
|
| 1484 |
+
the prime factors of ``r`` as keys and their respective multiplicities
|
| 1485 |
+
as values. For example:
|
| 1486 |
+
|
| 1487 |
+
>>> from sympy import factorrat, S
|
| 1488 |
+
>>> factorrat(S(8)/9) # 8/9 = (2**3) * (3**-2)
|
| 1489 |
+
{2: 3, 3: -2}
|
| 1490 |
+
>>> factorrat(S(-1)/987) # -1/789 = -1 * (3**-1) * (7**-1) * (47**-1)
|
| 1491 |
+
{-1: 1, 3: -1, 7: -1, 47: -1}
|
| 1492 |
+
|
| 1493 |
+
Please see the docstring for ``factorint`` for detailed explanations
|
| 1494 |
+
and examples of the following keywords:
|
| 1495 |
+
|
| 1496 |
+
- ``limit``: Integer limit up to which trial division is done
|
| 1497 |
+
- ``use_trial``: Toggle use of trial division
|
| 1498 |
+
- ``use_rho``: Toggle use of Pollard's rho method
|
| 1499 |
+
- ``use_pm1``: Toggle use of Pollard's p-1 method
|
| 1500 |
+
- ``verbose``: Toggle detailed printing of progress
|
| 1501 |
+
- ``multiple``: Toggle returning a list of factors or dict
|
| 1502 |
+
- ``visual``: Toggle product form of output
|
| 1503 |
+
"""
|
| 1504 |
+
if multiple:
|
| 1505 |
+
fac = factorrat(rat, limit=limit, use_trial=use_trial,
|
| 1506 |
+
use_rho=use_rho, use_pm1=use_pm1,
|
| 1507 |
+
verbose=verbose, visual=False, multiple=False)
|
| 1508 |
+
factorlist = sum(([p] * fac[p] if fac[p] > 0 else [S.One/p]*(-fac[p])
|
| 1509 |
+
for p, _ in sorted(fac.items(),
|
| 1510 |
+
key=lambda elem: elem[0]
|
| 1511 |
+
if elem[1] > 0
|
| 1512 |
+
else 1/elem[0])), [])
|
| 1513 |
+
return factorlist
|
| 1514 |
+
|
| 1515 |
+
f = factorint(rat.p, limit=limit, use_trial=use_trial,
|
| 1516 |
+
use_rho=use_rho, use_pm1=use_pm1,
|
| 1517 |
+
verbose=verbose).copy()
|
| 1518 |
+
f = defaultdict(int, f)
|
| 1519 |
+
for p, e in factorint(rat.q, limit=limit,
|
| 1520 |
+
use_trial=use_trial,
|
| 1521 |
+
use_rho=use_rho,
|
| 1522 |
+
use_pm1=use_pm1,
|
| 1523 |
+
verbose=verbose).items():
|
| 1524 |
+
f[p] += -e
|
| 1525 |
+
|
| 1526 |
+
if len(f) > 1 and 1 in f:
|
| 1527 |
+
del f[1]
|
| 1528 |
+
if not visual:
|
| 1529 |
+
return dict(f)
|
| 1530 |
+
else:
|
| 1531 |
+
if -1 in f:
|
| 1532 |
+
f.pop(-1)
|
| 1533 |
+
args = [S.NegativeOne]
|
| 1534 |
+
else:
|
| 1535 |
+
args = []
|
| 1536 |
+
args.extend([Pow(*i, evaluate=False)
|
| 1537 |
+
for i in sorted(f.items())])
|
| 1538 |
+
return Mul(*args, evaluate=False)
|
| 1539 |
+
|
| 1540 |
+
|
| 1541 |
+
def primefactors(n, limit=None, verbose=False, **kwargs):
|
| 1542 |
+
"""Return a sorted list of n's prime factors, ignoring multiplicity
|
| 1543 |
+
and any composite factor that remains if the limit was set too low
|
| 1544 |
+
for complete factorization. Unlike factorint(), primefactors() does
|
| 1545 |
+
not return -1 or 0.
|
| 1546 |
+
|
| 1547 |
+
Parameters
|
| 1548 |
+
==========
|
| 1549 |
+
|
| 1550 |
+
n : integer
|
| 1551 |
+
limit, verbose, **kwargs :
|
| 1552 |
+
Additional keyword arguments to be passed to ``factorint``.
|
| 1553 |
+
Since ``kwargs`` is new in version 1.13,
|
| 1554 |
+
``limit`` and ``verbose`` are retained for compatibility purposes.
|
| 1555 |
+
|
| 1556 |
+
Returns
|
| 1557 |
+
=======
|
| 1558 |
+
|
| 1559 |
+
list(int) : List of prime numbers dividing ``n``
|
| 1560 |
+
|
| 1561 |
+
Examples
|
| 1562 |
+
========
|
| 1563 |
+
|
| 1564 |
+
>>> from sympy.ntheory import primefactors, factorint, isprime
|
| 1565 |
+
>>> primefactors(6)
|
| 1566 |
+
[2, 3]
|
| 1567 |
+
>>> primefactors(-5)
|
| 1568 |
+
[5]
|
| 1569 |
+
|
| 1570 |
+
>>> sorted(factorint(123456).items())
|
| 1571 |
+
[(2, 6), (3, 1), (643, 1)]
|
| 1572 |
+
>>> primefactors(123456)
|
| 1573 |
+
[2, 3, 643]
|
| 1574 |
+
|
| 1575 |
+
>>> sorted(factorint(10000000001, limit=200).items())
|
| 1576 |
+
[(101, 1), (99009901, 1)]
|
| 1577 |
+
>>> isprime(99009901)
|
| 1578 |
+
False
|
| 1579 |
+
>>> primefactors(10000000001, limit=300)
|
| 1580 |
+
[101]
|
| 1581 |
+
|
| 1582 |
+
See Also
|
| 1583 |
+
========
|
| 1584 |
+
|
| 1585 |
+
factorint, divisors
|
| 1586 |
+
|
| 1587 |
+
"""
|
| 1588 |
+
n = int(n)
|
| 1589 |
+
kwargs.update({"visual": None, "multiple": False,
|
| 1590 |
+
"limit": limit, "verbose": verbose})
|
| 1591 |
+
factors = sorted(factorint(n=n, **kwargs).keys())
|
| 1592 |
+
# We want to calculate
|
| 1593 |
+
# s = [f for f in factors if isprime(f)]
|
| 1594 |
+
s = [f for f in factors[:-1:] if f not in [-1, 0, 1]]
|
| 1595 |
+
if factors and isprime(factors[-1]):
|
| 1596 |
+
s += [factors[-1]]
|
| 1597 |
+
return s
|
| 1598 |
+
|
| 1599 |
+
|
| 1600 |
+
def _divisors(n, proper=False):
|
| 1601 |
+
"""Helper function for divisors which generates the divisors.
|
| 1602 |
+
|
| 1603 |
+
Parameters
|
| 1604 |
+
==========
|
| 1605 |
+
|
| 1606 |
+
n : int
|
| 1607 |
+
a nonnegative integer
|
| 1608 |
+
proper: bool
|
| 1609 |
+
If `True`, returns the generator that outputs only the proper divisor (i.e., excluding n).
|
| 1610 |
+
|
| 1611 |
+
"""
|
| 1612 |
+
if n <= 1:
|
| 1613 |
+
if not proper and n:
|
| 1614 |
+
yield 1
|
| 1615 |
+
return
|
| 1616 |
+
|
| 1617 |
+
factordict = factorint(n)
|
| 1618 |
+
ps = sorted(factordict.keys())
|
| 1619 |
+
|
| 1620 |
+
def rec_gen(n=0):
|
| 1621 |
+
if n == len(ps):
|
| 1622 |
+
yield 1
|
| 1623 |
+
else:
|
| 1624 |
+
pows = [1]
|
| 1625 |
+
for _ in range(factordict[ps[n]]):
|
| 1626 |
+
pows.append(pows[-1] * ps[n])
|
| 1627 |
+
yield from (p * q for q in rec_gen(n + 1) for p in pows)
|
| 1628 |
+
|
| 1629 |
+
if proper:
|
| 1630 |
+
yield from (p for p in rec_gen() if p != n)
|
| 1631 |
+
else:
|
| 1632 |
+
yield from rec_gen()
|
| 1633 |
+
|
| 1634 |
+
|
| 1635 |
+
def divisors(n, generator=False, proper=False):
|
| 1636 |
+
r"""
|
| 1637 |
+
Return all divisors of n sorted from 1..n by default.
|
| 1638 |
+
If generator is ``True`` an unordered generator is returned.
|
| 1639 |
+
|
| 1640 |
+
The number of divisors of n can be quite large if there are many
|
| 1641 |
+
prime factors (counting repeated factors). If only the number of
|
| 1642 |
+
factors is desired use divisor_count(n).
|
| 1643 |
+
|
| 1644 |
+
Examples
|
| 1645 |
+
========
|
| 1646 |
+
|
| 1647 |
+
>>> from sympy import divisors, divisor_count
|
| 1648 |
+
>>> divisors(24)
|
| 1649 |
+
[1, 2, 3, 4, 6, 8, 12, 24]
|
| 1650 |
+
>>> divisor_count(24)
|
| 1651 |
+
8
|
| 1652 |
+
|
| 1653 |
+
>>> list(divisors(120, generator=True))
|
| 1654 |
+
[1, 2, 4, 8, 3, 6, 12, 24, 5, 10, 20, 40, 15, 30, 60, 120]
|
| 1655 |
+
|
| 1656 |
+
Notes
|
| 1657 |
+
=====
|
| 1658 |
+
|
| 1659 |
+
This is a slightly modified version of Tim Peters referenced at:
|
| 1660 |
+
https://stackoverflow.com/questions/1010381/python-factorization
|
| 1661 |
+
|
| 1662 |
+
See Also
|
| 1663 |
+
========
|
| 1664 |
+
|
| 1665 |
+
primefactors, factorint, divisor_count
|
| 1666 |
+
"""
|
| 1667 |
+
rv = _divisors(as_int(abs(n)), proper)
|
| 1668 |
+
return rv if generator else sorted(rv)
|
| 1669 |
+
|
| 1670 |
+
|
| 1671 |
+
def divisor_count(n, modulus=1, proper=False):
|
| 1672 |
+
"""
|
| 1673 |
+
Return the number of divisors of ``n``. If ``modulus`` is not 1 then only
|
| 1674 |
+
those that are divisible by ``modulus`` are counted. If ``proper`` is True
|
| 1675 |
+
then the divisor of ``n`` will not be counted.
|
| 1676 |
+
|
| 1677 |
+
Examples
|
| 1678 |
+
========
|
| 1679 |
+
|
| 1680 |
+
>>> from sympy import divisor_count
|
| 1681 |
+
>>> divisor_count(6)
|
| 1682 |
+
4
|
| 1683 |
+
>>> divisor_count(6, 2)
|
| 1684 |
+
2
|
| 1685 |
+
>>> divisor_count(6, proper=True)
|
| 1686 |
+
3
|
| 1687 |
+
|
| 1688 |
+
See Also
|
| 1689 |
+
========
|
| 1690 |
+
|
| 1691 |
+
factorint, divisors, totient, proper_divisor_count
|
| 1692 |
+
|
| 1693 |
+
"""
|
| 1694 |
+
|
| 1695 |
+
if not modulus:
|
| 1696 |
+
return 0
|
| 1697 |
+
elif modulus != 1:
|
| 1698 |
+
n, r = divmod(n, modulus)
|
| 1699 |
+
if r:
|
| 1700 |
+
return 0
|
| 1701 |
+
if n == 0:
|
| 1702 |
+
return 0
|
| 1703 |
+
n = Mul(*[v + 1 for k, v in factorint(n).items() if k > 1])
|
| 1704 |
+
if n and proper:
|
| 1705 |
+
n -= 1
|
| 1706 |
+
return n
|
| 1707 |
+
|
| 1708 |
+
|
| 1709 |
+
def proper_divisors(n, generator=False):
|
| 1710 |
+
"""
|
| 1711 |
+
Return all divisors of n except n, sorted by default.
|
| 1712 |
+
If generator is ``True`` an unordered generator is returned.
|
| 1713 |
+
|
| 1714 |
+
Examples
|
| 1715 |
+
========
|
| 1716 |
+
|
| 1717 |
+
>>> from sympy import proper_divisors, proper_divisor_count
|
| 1718 |
+
>>> proper_divisors(24)
|
| 1719 |
+
[1, 2, 3, 4, 6, 8, 12]
|
| 1720 |
+
>>> proper_divisor_count(24)
|
| 1721 |
+
7
|
| 1722 |
+
>>> list(proper_divisors(120, generator=True))
|
| 1723 |
+
[1, 2, 4, 8, 3, 6, 12, 24, 5, 10, 20, 40, 15, 30, 60]
|
| 1724 |
+
|
| 1725 |
+
See Also
|
| 1726 |
+
========
|
| 1727 |
+
|
| 1728 |
+
factorint, divisors, proper_divisor_count
|
| 1729 |
+
|
| 1730 |
+
"""
|
| 1731 |
+
return divisors(n, generator=generator, proper=True)
|
| 1732 |
+
|
| 1733 |
+
|
| 1734 |
+
def proper_divisor_count(n, modulus=1):
|
| 1735 |
+
"""
|
| 1736 |
+
Return the number of proper divisors of ``n``.
|
| 1737 |
+
|
| 1738 |
+
Examples
|
| 1739 |
+
========
|
| 1740 |
+
|
| 1741 |
+
>>> from sympy import proper_divisor_count
|
| 1742 |
+
>>> proper_divisor_count(6)
|
| 1743 |
+
3
|
| 1744 |
+
>>> proper_divisor_count(6, modulus=2)
|
| 1745 |
+
1
|
| 1746 |
+
|
| 1747 |
+
See Also
|
| 1748 |
+
========
|
| 1749 |
+
|
| 1750 |
+
divisors, proper_divisors, divisor_count
|
| 1751 |
+
|
| 1752 |
+
"""
|
| 1753 |
+
return divisor_count(n, modulus=modulus, proper=True)
|
| 1754 |
+
|
| 1755 |
+
|
| 1756 |
+
def _udivisors(n):
|
| 1757 |
+
"""Helper function for udivisors which generates the unitary divisors.
|
| 1758 |
+
|
| 1759 |
+
Parameters
|
| 1760 |
+
==========
|
| 1761 |
+
|
| 1762 |
+
n : int
|
| 1763 |
+
a nonnegative integer
|
| 1764 |
+
|
| 1765 |
+
"""
|
| 1766 |
+
if n <= 1:
|
| 1767 |
+
if n == 1:
|
| 1768 |
+
yield 1
|
| 1769 |
+
return
|
| 1770 |
+
|
| 1771 |
+
factorpows = [p**e for p, e in factorint(n).items()]
|
| 1772 |
+
# We want to calculate
|
| 1773 |
+
# yield from (math.prod(s) for s in powersets(factorpows))
|
| 1774 |
+
for i in range(2**len(factorpows)):
|
| 1775 |
+
d = 1
|
| 1776 |
+
for k in range(i.bit_length()):
|
| 1777 |
+
if i & 1:
|
| 1778 |
+
d *= factorpows[k]
|
| 1779 |
+
i >>= 1
|
| 1780 |
+
yield d
|
| 1781 |
+
|
| 1782 |
+
|
| 1783 |
+
def udivisors(n, generator=False):
|
| 1784 |
+
r"""
|
| 1785 |
+
Return all unitary divisors of n sorted from 1..n by default.
|
| 1786 |
+
If generator is ``True`` an unordered generator is returned.
|
| 1787 |
+
|
| 1788 |
+
The number of unitary divisors of n can be quite large if there are many
|
| 1789 |
+
prime factors. If only the number of unitary divisors is desired use
|
| 1790 |
+
udivisor_count(n).
|
| 1791 |
+
|
| 1792 |
+
Examples
|
| 1793 |
+
========
|
| 1794 |
+
|
| 1795 |
+
>>> from sympy.ntheory.factor_ import udivisors, udivisor_count
|
| 1796 |
+
>>> udivisors(15)
|
| 1797 |
+
[1, 3, 5, 15]
|
| 1798 |
+
>>> udivisor_count(15)
|
| 1799 |
+
4
|
| 1800 |
+
|
| 1801 |
+
>>> sorted(udivisors(120, generator=True))
|
| 1802 |
+
[1, 3, 5, 8, 15, 24, 40, 120]
|
| 1803 |
+
|
| 1804 |
+
See Also
|
| 1805 |
+
========
|
| 1806 |
+
|
| 1807 |
+
primefactors, factorint, divisors, divisor_count, udivisor_count
|
| 1808 |
+
|
| 1809 |
+
References
|
| 1810 |
+
==========
|
| 1811 |
+
|
| 1812 |
+
.. [1] https://en.wikipedia.org/wiki/Unitary_divisor
|
| 1813 |
+
.. [2] https://mathworld.wolfram.com/UnitaryDivisor.html
|
| 1814 |
+
|
| 1815 |
+
"""
|
| 1816 |
+
rv = _udivisors(as_int(abs(n)))
|
| 1817 |
+
return rv if generator else sorted(rv)
|
| 1818 |
+
|
| 1819 |
+
|
| 1820 |
+
def udivisor_count(n):
|
| 1821 |
+
"""
|
| 1822 |
+
Return the number of unitary divisors of ``n``.
|
| 1823 |
+
|
| 1824 |
+
Parameters
|
| 1825 |
+
==========
|
| 1826 |
+
|
| 1827 |
+
n : integer
|
| 1828 |
+
|
| 1829 |
+
Examples
|
| 1830 |
+
========
|
| 1831 |
+
|
| 1832 |
+
>>> from sympy.ntheory.factor_ import udivisor_count
|
| 1833 |
+
>>> udivisor_count(120)
|
| 1834 |
+
8
|
| 1835 |
+
|
| 1836 |
+
See Also
|
| 1837 |
+
========
|
| 1838 |
+
|
| 1839 |
+
factorint, divisors, udivisors, divisor_count, totient
|
| 1840 |
+
|
| 1841 |
+
References
|
| 1842 |
+
==========
|
| 1843 |
+
|
| 1844 |
+
.. [1] https://mathworld.wolfram.com/UnitaryDivisorFunction.html
|
| 1845 |
+
|
| 1846 |
+
"""
|
| 1847 |
+
|
| 1848 |
+
if n == 0:
|
| 1849 |
+
return 0
|
| 1850 |
+
return 2**len([p for p in factorint(n) if p > 1])
|
| 1851 |
+
|
| 1852 |
+
|
| 1853 |
+
def _antidivisors(n):
|
| 1854 |
+
"""Helper function for antidivisors which generates the antidivisors.
|
| 1855 |
+
|
| 1856 |
+
Parameters
|
| 1857 |
+
==========
|
| 1858 |
+
|
| 1859 |
+
n : int
|
| 1860 |
+
a nonnegative integer
|
| 1861 |
+
|
| 1862 |
+
"""
|
| 1863 |
+
if n <= 2:
|
| 1864 |
+
return
|
| 1865 |
+
for d in _divisors(n):
|
| 1866 |
+
y = 2*d
|
| 1867 |
+
if n > y and n % y:
|
| 1868 |
+
yield y
|
| 1869 |
+
for d in _divisors(2*n-1):
|
| 1870 |
+
if n > d >= 2 and n % d:
|
| 1871 |
+
yield d
|
| 1872 |
+
for d in _divisors(2*n+1):
|
| 1873 |
+
if n > d >= 2 and n % d:
|
| 1874 |
+
yield d
|
| 1875 |
+
|
| 1876 |
+
|
| 1877 |
+
def antidivisors(n, generator=False):
|
| 1878 |
+
r"""
|
| 1879 |
+
Return all antidivisors of n sorted from 1..n by default.
|
| 1880 |
+
|
| 1881 |
+
Antidivisors [1]_ of n are numbers that do not divide n by the largest
|
| 1882 |
+
possible margin. If generator is True an unordered generator is returned.
|
| 1883 |
+
|
| 1884 |
+
Examples
|
| 1885 |
+
========
|
| 1886 |
+
|
| 1887 |
+
>>> from sympy.ntheory.factor_ import antidivisors
|
| 1888 |
+
>>> antidivisors(24)
|
| 1889 |
+
[7, 16]
|
| 1890 |
+
|
| 1891 |
+
>>> sorted(antidivisors(128, generator=True))
|
| 1892 |
+
[3, 5, 15, 17, 51, 85]
|
| 1893 |
+
|
| 1894 |
+
See Also
|
| 1895 |
+
========
|
| 1896 |
+
|
| 1897 |
+
primefactors, factorint, divisors, divisor_count, antidivisor_count
|
| 1898 |
+
|
| 1899 |
+
References
|
| 1900 |
+
==========
|
| 1901 |
+
|
| 1902 |
+
.. [1] definition is described in https://oeis.org/A066272/a066272a.html
|
| 1903 |
+
|
| 1904 |
+
"""
|
| 1905 |
+
rv = _antidivisors(as_int(abs(n)))
|
| 1906 |
+
return rv if generator else sorted(rv)
|
| 1907 |
+
|
| 1908 |
+
|
| 1909 |
+
def antidivisor_count(n):
|
| 1910 |
+
"""
|
| 1911 |
+
Return the number of antidivisors [1]_ of ``n``.
|
| 1912 |
+
|
| 1913 |
+
Parameters
|
| 1914 |
+
==========
|
| 1915 |
+
|
| 1916 |
+
n : integer
|
| 1917 |
+
|
| 1918 |
+
Examples
|
| 1919 |
+
========
|
| 1920 |
+
|
| 1921 |
+
>>> from sympy.ntheory.factor_ import antidivisor_count
|
| 1922 |
+
>>> antidivisor_count(13)
|
| 1923 |
+
4
|
| 1924 |
+
>>> antidivisor_count(27)
|
| 1925 |
+
5
|
| 1926 |
+
|
| 1927 |
+
See Also
|
| 1928 |
+
========
|
| 1929 |
+
|
| 1930 |
+
factorint, divisors, antidivisors, divisor_count, totient
|
| 1931 |
+
|
| 1932 |
+
References
|
| 1933 |
+
==========
|
| 1934 |
+
|
| 1935 |
+
.. [1] formula from https://oeis.org/A066272
|
| 1936 |
+
|
| 1937 |
+
"""
|
| 1938 |
+
|
| 1939 |
+
n = as_int(abs(n))
|
| 1940 |
+
if n <= 2:
|
| 1941 |
+
return 0
|
| 1942 |
+
return divisor_count(2*n - 1) + divisor_count(2*n + 1) + \
|
| 1943 |
+
divisor_count(n) - divisor_count(n, 2) - 5
|
| 1944 |
+
|
| 1945 |
+
@deprecated("""\
|
| 1946 |
+
The `sympy.ntheory.factor_.totient` has been moved to `sympy.functions.combinatorial.numbers.totient`.""",
|
| 1947 |
+
deprecated_since_version="1.13",
|
| 1948 |
+
active_deprecations_target='deprecated-ntheory-symbolic-functions')
|
| 1949 |
+
def totient(n):
|
| 1950 |
+
r"""
|
| 1951 |
+
Calculate the Euler totient function phi(n)
|
| 1952 |
+
|
| 1953 |
+
.. deprecated:: 1.13
|
| 1954 |
+
|
| 1955 |
+
The ``totient`` function is deprecated. Use :class:`sympy.functions.combinatorial.numbers.totient`
|
| 1956 |
+
instead. See its documentation for more information. See
|
| 1957 |
+
:ref:`deprecated-ntheory-symbolic-functions` for details.
|
| 1958 |
+
|
| 1959 |
+
``totient(n)`` or `\phi(n)` is the number of positive integers `\leq` n
|
| 1960 |
+
that are relatively prime to n.
|
| 1961 |
+
|
| 1962 |
+
Parameters
|
| 1963 |
+
==========
|
| 1964 |
+
|
| 1965 |
+
n : integer
|
| 1966 |
+
|
| 1967 |
+
Examples
|
| 1968 |
+
========
|
| 1969 |
+
|
| 1970 |
+
>>> from sympy.functions.combinatorial.numbers import totient
|
| 1971 |
+
>>> totient(1)
|
| 1972 |
+
1
|
| 1973 |
+
>>> totient(25)
|
| 1974 |
+
20
|
| 1975 |
+
>>> totient(45) == totient(5)*totient(9)
|
| 1976 |
+
True
|
| 1977 |
+
|
| 1978 |
+
See Also
|
| 1979 |
+
========
|
| 1980 |
+
|
| 1981 |
+
divisor_count
|
| 1982 |
+
|
| 1983 |
+
References
|
| 1984 |
+
==========
|
| 1985 |
+
|
| 1986 |
+
.. [1] https://en.wikipedia.org/wiki/Euler%27s_totient_function
|
| 1987 |
+
.. [2] https://mathworld.wolfram.com/TotientFunction.html
|
| 1988 |
+
|
| 1989 |
+
"""
|
| 1990 |
+
from sympy.functions.combinatorial.numbers import totient as _totient
|
| 1991 |
+
return _totient(n)
|
| 1992 |
+
|
| 1993 |
+
|
| 1994 |
+
@deprecated("""\
|
| 1995 |
+
The `sympy.ntheory.factor_.reduced_totient` has been moved to `sympy.functions.combinatorial.numbers.reduced_totient`.""",
|
| 1996 |
+
deprecated_since_version="1.13",
|
| 1997 |
+
active_deprecations_target='deprecated-ntheory-symbolic-functions')
|
| 1998 |
+
def reduced_totient(n):
|
| 1999 |
+
r"""
|
| 2000 |
+
Calculate the Carmichael reduced totient function lambda(n)
|
| 2001 |
+
|
| 2002 |
+
.. deprecated:: 1.13
|
| 2003 |
+
|
| 2004 |
+
The ``reduced_totient`` function is deprecated. Use :class:`sympy.functions.combinatorial.numbers.reduced_totient`
|
| 2005 |
+
instead. See its documentation for more information. See
|
| 2006 |
+
:ref:`deprecated-ntheory-symbolic-functions` for details.
|
| 2007 |
+
|
| 2008 |
+
``reduced_totient(n)`` or `\lambda(n)` is the smallest m > 0 such that
|
| 2009 |
+
`k^m \equiv 1 \mod n` for all k relatively prime to n.
|
| 2010 |
+
|
| 2011 |
+
Examples
|
| 2012 |
+
========
|
| 2013 |
+
|
| 2014 |
+
>>> from sympy.functions.combinatorial.numbers import reduced_totient
|
| 2015 |
+
>>> reduced_totient(1)
|
| 2016 |
+
1
|
| 2017 |
+
>>> reduced_totient(8)
|
| 2018 |
+
2
|
| 2019 |
+
>>> reduced_totient(30)
|
| 2020 |
+
4
|
| 2021 |
+
|
| 2022 |
+
See Also
|
| 2023 |
+
========
|
| 2024 |
+
|
| 2025 |
+
totient
|
| 2026 |
+
|
| 2027 |
+
References
|
| 2028 |
+
==========
|
| 2029 |
+
|
| 2030 |
+
.. [1] https://en.wikipedia.org/wiki/Carmichael_function
|
| 2031 |
+
.. [2] https://mathworld.wolfram.com/CarmichaelFunction.html
|
| 2032 |
+
|
| 2033 |
+
"""
|
| 2034 |
+
from sympy.functions.combinatorial.numbers import reduced_totient as _reduced_totient
|
| 2035 |
+
return _reduced_totient(n)
|
| 2036 |
+
|
| 2037 |
+
|
| 2038 |
+
@deprecated("""\
|
| 2039 |
+
The `sympy.ntheory.factor_.divisor_sigma` has been moved to `sympy.functions.combinatorial.numbers.divisor_sigma`.""",
|
| 2040 |
+
deprecated_since_version="1.13",
|
| 2041 |
+
active_deprecations_target='deprecated-ntheory-symbolic-functions')
|
| 2042 |
+
def divisor_sigma(n, k=1):
|
| 2043 |
+
r"""
|
| 2044 |
+
Calculate the divisor function `\sigma_k(n)` for positive integer n
|
| 2045 |
+
|
| 2046 |
+
.. deprecated:: 1.13
|
| 2047 |
+
|
| 2048 |
+
The ``divisor_sigma`` function is deprecated. Use :class:`sympy.functions.combinatorial.numbers.divisor_sigma`
|
| 2049 |
+
instead. See its documentation for more information. See
|
| 2050 |
+
:ref:`deprecated-ntheory-symbolic-functions` for details.
|
| 2051 |
+
|
| 2052 |
+
``divisor_sigma(n, k)`` is equal to ``sum([x**k for x in divisors(n)])``
|
| 2053 |
+
|
| 2054 |
+
If n's prime factorization is:
|
| 2055 |
+
|
| 2056 |
+
.. math ::
|
| 2057 |
+
n = \prod_{i=1}^\omega p_i^{m_i},
|
| 2058 |
+
|
| 2059 |
+
then
|
| 2060 |
+
|
| 2061 |
+
.. math ::
|
| 2062 |
+
\sigma_k(n) = \prod_{i=1}^\omega (1+p_i^k+p_i^{2k}+\cdots
|
| 2063 |
+
+ p_i^{m_ik}).
|
| 2064 |
+
|
| 2065 |
+
Parameters
|
| 2066 |
+
==========
|
| 2067 |
+
|
| 2068 |
+
n : integer
|
| 2069 |
+
|
| 2070 |
+
k : integer, optional
|
| 2071 |
+
power of divisors in the sum
|
| 2072 |
+
|
| 2073 |
+
for k = 0, 1:
|
| 2074 |
+
``divisor_sigma(n, 0)`` is equal to ``divisor_count(n)``
|
| 2075 |
+
``divisor_sigma(n, 1)`` is equal to ``sum(divisors(n))``
|
| 2076 |
+
|
| 2077 |
+
Default for k is 1.
|
| 2078 |
+
|
| 2079 |
+
Examples
|
| 2080 |
+
========
|
| 2081 |
+
|
| 2082 |
+
>>> from sympy.functions.combinatorial.numbers import divisor_sigma
|
| 2083 |
+
>>> divisor_sigma(18, 0)
|
| 2084 |
+
6
|
| 2085 |
+
>>> divisor_sigma(39, 1)
|
| 2086 |
+
56
|
| 2087 |
+
>>> divisor_sigma(12, 2)
|
| 2088 |
+
210
|
| 2089 |
+
>>> divisor_sigma(37)
|
| 2090 |
+
38
|
| 2091 |
+
|
| 2092 |
+
See Also
|
| 2093 |
+
========
|
| 2094 |
+
|
| 2095 |
+
divisor_count, totient, divisors, factorint
|
| 2096 |
+
|
| 2097 |
+
References
|
| 2098 |
+
==========
|
| 2099 |
+
|
| 2100 |
+
.. [1] https://en.wikipedia.org/wiki/Divisor_function
|
| 2101 |
+
|
| 2102 |
+
"""
|
| 2103 |
+
from sympy.functions.combinatorial.numbers import divisor_sigma as func_divisor_sigma
|
| 2104 |
+
return func_divisor_sigma(n, k)
|
| 2105 |
+
|
| 2106 |
+
|
| 2107 |
+
def _divisor_sigma(n:int, k:int=1) -> int:
|
| 2108 |
+
r""" Calculate the divisor function `\sigma_k(n)` for positive integer n
|
| 2109 |
+
|
| 2110 |
+
Parameters
|
| 2111 |
+
==========
|
| 2112 |
+
|
| 2113 |
+
n : int
|
| 2114 |
+
positive integer
|
| 2115 |
+
k : int
|
| 2116 |
+
nonnegative integer
|
| 2117 |
+
|
| 2118 |
+
See Also
|
| 2119 |
+
========
|
| 2120 |
+
|
| 2121 |
+
sympy.functions.combinatorial.numbers.divisor_sigma
|
| 2122 |
+
|
| 2123 |
+
"""
|
| 2124 |
+
if k == 0:
|
| 2125 |
+
return math.prod(e + 1 for e in factorint(n).values())
|
| 2126 |
+
return math.prod((p**(k*(e + 1)) - 1)//(p**k - 1) for p, e in factorint(n).items())
|
| 2127 |
+
|
| 2128 |
+
|
| 2129 |
+
def core(n, t=2):
|
| 2130 |
+
r"""
|
| 2131 |
+
Calculate core(n, t) = `core_t(n)` of a positive integer n
|
| 2132 |
+
|
| 2133 |
+
``core_2(n)`` is equal to the squarefree part of n
|
| 2134 |
+
|
| 2135 |
+
If n's prime factorization is:
|
| 2136 |
+
|
| 2137 |
+
.. math ::
|
| 2138 |
+
n = \prod_{i=1}^\omega p_i^{m_i},
|
| 2139 |
+
|
| 2140 |
+
then
|
| 2141 |
+
|
| 2142 |
+
.. math ::
|
| 2143 |
+
core_t(n) = \prod_{i=1}^\omega p_i^{m_i \mod t}.
|
| 2144 |
+
|
| 2145 |
+
Parameters
|
| 2146 |
+
==========
|
| 2147 |
+
|
| 2148 |
+
n : integer
|
| 2149 |
+
|
| 2150 |
+
t : integer
|
| 2151 |
+
core(n, t) calculates the t-th power free part of n
|
| 2152 |
+
|
| 2153 |
+
``core(n, 2)`` is the squarefree part of ``n``
|
| 2154 |
+
``core(n, 3)`` is the cubefree part of ``n``
|
| 2155 |
+
|
| 2156 |
+
Default for t is 2.
|
| 2157 |
+
|
| 2158 |
+
Examples
|
| 2159 |
+
========
|
| 2160 |
+
|
| 2161 |
+
>>> from sympy.ntheory.factor_ import core
|
| 2162 |
+
>>> core(24, 2)
|
| 2163 |
+
6
|
| 2164 |
+
>>> core(9424, 3)
|
| 2165 |
+
1178
|
| 2166 |
+
>>> core(379238)
|
| 2167 |
+
379238
|
| 2168 |
+
>>> core(15**11, 10)
|
| 2169 |
+
15
|
| 2170 |
+
|
| 2171 |
+
See Also
|
| 2172 |
+
========
|
| 2173 |
+
|
| 2174 |
+
factorint, sympy.solvers.diophantine.diophantine.square_factor
|
| 2175 |
+
|
| 2176 |
+
References
|
| 2177 |
+
==========
|
| 2178 |
+
|
| 2179 |
+
.. [1] https://en.wikipedia.org/wiki/Square-free_integer#Squarefree_core
|
| 2180 |
+
|
| 2181 |
+
"""
|
| 2182 |
+
|
| 2183 |
+
n = as_int(n)
|
| 2184 |
+
t = as_int(t)
|
| 2185 |
+
if n <= 0:
|
| 2186 |
+
raise ValueError("n must be a positive integer")
|
| 2187 |
+
elif t <= 1:
|
| 2188 |
+
raise ValueError("t must be >= 2")
|
| 2189 |
+
else:
|
| 2190 |
+
y = 1
|
| 2191 |
+
for p, e in factorint(n).items():
|
| 2192 |
+
y *= p**(e % t)
|
| 2193 |
+
return y
|
| 2194 |
+
|
| 2195 |
+
|
| 2196 |
+
@deprecated("""\
|
| 2197 |
+
The `sympy.ntheory.factor_.udivisor_sigma` has been moved to `sympy.functions.combinatorial.numbers.udivisor_sigma`.""",
|
| 2198 |
+
deprecated_since_version="1.13",
|
| 2199 |
+
active_deprecations_target='deprecated-ntheory-symbolic-functions')
|
| 2200 |
+
def udivisor_sigma(n, k=1):
|
| 2201 |
+
r"""
|
| 2202 |
+
Calculate the unitary divisor function `\sigma_k^*(n)` for positive integer n
|
| 2203 |
+
|
| 2204 |
+
.. deprecated:: 1.13
|
| 2205 |
+
|
| 2206 |
+
The ``udivisor_sigma`` function is deprecated. Use :class:`sympy.functions.combinatorial.numbers.udivisor_sigma`
|
| 2207 |
+
instead. See its documentation for more information. See
|
| 2208 |
+
:ref:`deprecated-ntheory-symbolic-functions` for details.
|
| 2209 |
+
|
| 2210 |
+
``udivisor_sigma(n, k)`` is equal to ``sum([x**k for x in udivisors(n)])``
|
| 2211 |
+
|
| 2212 |
+
If n's prime factorization is:
|
| 2213 |
+
|
| 2214 |
+
.. math ::
|
| 2215 |
+
n = \prod_{i=1}^\omega p_i^{m_i},
|
| 2216 |
+
|
| 2217 |
+
then
|
| 2218 |
+
|
| 2219 |
+
.. math ::
|
| 2220 |
+
\sigma_k^*(n) = \prod_{i=1}^\omega (1+ p_i^{m_ik}).
|
| 2221 |
+
|
| 2222 |
+
Parameters
|
| 2223 |
+
==========
|
| 2224 |
+
|
| 2225 |
+
k : power of divisors in the sum
|
| 2226 |
+
|
| 2227 |
+
for k = 0, 1:
|
| 2228 |
+
``udivisor_sigma(n, 0)`` is equal to ``udivisor_count(n)``
|
| 2229 |
+
``udivisor_sigma(n, 1)`` is equal to ``sum(udivisors(n))``
|
| 2230 |
+
|
| 2231 |
+
Default for k is 1.
|
| 2232 |
+
|
| 2233 |
+
Examples
|
| 2234 |
+
========
|
| 2235 |
+
|
| 2236 |
+
>>> from sympy.functions.combinatorial.numbers import udivisor_sigma
|
| 2237 |
+
>>> udivisor_sigma(18, 0)
|
| 2238 |
+
4
|
| 2239 |
+
>>> udivisor_sigma(74, 1)
|
| 2240 |
+
114
|
| 2241 |
+
>>> udivisor_sigma(36, 3)
|
| 2242 |
+
47450
|
| 2243 |
+
>>> udivisor_sigma(111)
|
| 2244 |
+
152
|
| 2245 |
+
|
| 2246 |
+
See Also
|
| 2247 |
+
========
|
| 2248 |
+
|
| 2249 |
+
divisor_count, totient, divisors, udivisors, udivisor_count, divisor_sigma,
|
| 2250 |
+
factorint
|
| 2251 |
+
|
| 2252 |
+
References
|
| 2253 |
+
==========
|
| 2254 |
+
|
| 2255 |
+
.. [1] https://mathworld.wolfram.com/UnitaryDivisorFunction.html
|
| 2256 |
+
|
| 2257 |
+
"""
|
| 2258 |
+
from sympy.functions.combinatorial.numbers import udivisor_sigma as _udivisor_sigma
|
| 2259 |
+
return _udivisor_sigma(n, k)
|
| 2260 |
+
|
| 2261 |
+
|
| 2262 |
+
@deprecated("""\
|
| 2263 |
+
The `sympy.ntheory.factor_.primenu` has been moved to `sympy.functions.combinatorial.numbers.primenu`.""",
|
| 2264 |
+
deprecated_since_version="1.13",
|
| 2265 |
+
active_deprecations_target='deprecated-ntheory-symbolic-functions')
|
| 2266 |
+
def primenu(n):
|
| 2267 |
+
r"""
|
| 2268 |
+
Calculate the number of distinct prime factors for a positive integer n.
|
| 2269 |
+
|
| 2270 |
+
.. deprecated:: 1.13
|
| 2271 |
+
|
| 2272 |
+
The ``primenu`` function is deprecated. Use :class:`sympy.functions.combinatorial.numbers.primenu`
|
| 2273 |
+
instead. See its documentation for more information. See
|
| 2274 |
+
:ref:`deprecated-ntheory-symbolic-functions` for details.
|
| 2275 |
+
|
| 2276 |
+
If n's prime factorization is:
|
| 2277 |
+
|
| 2278 |
+
.. math ::
|
| 2279 |
+
n = \prod_{i=1}^k p_i^{m_i},
|
| 2280 |
+
|
| 2281 |
+
then ``primenu(n)`` or `\nu(n)` is:
|
| 2282 |
+
|
| 2283 |
+
.. math ::
|
| 2284 |
+
\nu(n) = k.
|
| 2285 |
+
|
| 2286 |
+
Examples
|
| 2287 |
+
========
|
| 2288 |
+
|
| 2289 |
+
>>> from sympy.functions.combinatorial.numbers import primenu
|
| 2290 |
+
>>> primenu(1)
|
| 2291 |
+
0
|
| 2292 |
+
>>> primenu(30)
|
| 2293 |
+
3
|
| 2294 |
+
|
| 2295 |
+
See Also
|
| 2296 |
+
========
|
| 2297 |
+
|
| 2298 |
+
factorint
|
| 2299 |
+
|
| 2300 |
+
References
|
| 2301 |
+
==========
|
| 2302 |
+
|
| 2303 |
+
.. [1] https://mathworld.wolfram.com/PrimeFactor.html
|
| 2304 |
+
|
| 2305 |
+
"""
|
| 2306 |
+
from sympy.functions.combinatorial.numbers import primenu as _primenu
|
| 2307 |
+
return _primenu(n)
|
| 2308 |
+
|
| 2309 |
+
|
| 2310 |
+
@deprecated("""\
|
| 2311 |
+
The `sympy.ntheory.factor_.primeomega` has been moved to `sympy.functions.combinatorial.numbers.primeomega`.""",
|
| 2312 |
+
deprecated_since_version="1.13",
|
| 2313 |
+
active_deprecations_target='deprecated-ntheory-symbolic-functions')
|
| 2314 |
+
def primeomega(n):
|
| 2315 |
+
r"""
|
| 2316 |
+
Calculate the number of prime factors counting multiplicities for a
|
| 2317 |
+
positive integer n.
|
| 2318 |
+
|
| 2319 |
+
.. deprecated:: 1.13
|
| 2320 |
+
|
| 2321 |
+
The ``primeomega`` function is deprecated. Use :class:`sympy.functions.combinatorial.numbers.primeomega`
|
| 2322 |
+
instead. See its documentation for more information. See
|
| 2323 |
+
:ref:`deprecated-ntheory-symbolic-functions` for details.
|
| 2324 |
+
|
| 2325 |
+
If n's prime factorization is:
|
| 2326 |
+
|
| 2327 |
+
.. math ::
|
| 2328 |
+
n = \prod_{i=1}^k p_i^{m_i},
|
| 2329 |
+
|
| 2330 |
+
then ``primeomega(n)`` or `\Omega(n)` is:
|
| 2331 |
+
|
| 2332 |
+
.. math ::
|
| 2333 |
+
\Omega(n) = \sum_{i=1}^k m_i.
|
| 2334 |
+
|
| 2335 |
+
Examples
|
| 2336 |
+
========
|
| 2337 |
+
|
| 2338 |
+
>>> from sympy.functions.combinatorial.numbers import primeomega
|
| 2339 |
+
>>> primeomega(1)
|
| 2340 |
+
0
|
| 2341 |
+
>>> primeomega(20)
|
| 2342 |
+
3
|
| 2343 |
+
|
| 2344 |
+
See Also
|
| 2345 |
+
========
|
| 2346 |
+
|
| 2347 |
+
factorint
|
| 2348 |
+
|
| 2349 |
+
References
|
| 2350 |
+
==========
|
| 2351 |
+
|
| 2352 |
+
.. [1] https://mathworld.wolfram.com/PrimeFactor.html
|
| 2353 |
+
|
| 2354 |
+
"""
|
| 2355 |
+
from sympy.functions.combinatorial.numbers import primeomega as _primeomega
|
| 2356 |
+
return _primeomega(n)
|
| 2357 |
+
|
| 2358 |
+
|
| 2359 |
+
def mersenne_prime_exponent(nth):
|
| 2360 |
+
"""Returns the exponent ``i`` for the nth Mersenne prime (which
|
| 2361 |
+
has the form `2^i - 1`).
|
| 2362 |
+
|
| 2363 |
+
Examples
|
| 2364 |
+
========
|
| 2365 |
+
|
| 2366 |
+
>>> from sympy.ntheory.factor_ import mersenne_prime_exponent
|
| 2367 |
+
>>> mersenne_prime_exponent(1)
|
| 2368 |
+
2
|
| 2369 |
+
>>> mersenne_prime_exponent(20)
|
| 2370 |
+
4423
|
| 2371 |
+
"""
|
| 2372 |
+
n = as_int(nth)
|
| 2373 |
+
if n < 1:
|
| 2374 |
+
raise ValueError("nth must be a positive integer; mersenne_prime_exponent(1) == 2")
|
| 2375 |
+
if n > 51:
|
| 2376 |
+
raise ValueError("There are only 51 perfect numbers; nth must be less than or equal to 51")
|
| 2377 |
+
return MERSENNE_PRIME_EXPONENTS[n - 1]
|
| 2378 |
+
|
| 2379 |
+
|
| 2380 |
+
def is_perfect(n):
|
| 2381 |
+
"""Returns True if ``n`` is a perfect number, else False.
|
| 2382 |
+
|
| 2383 |
+
A perfect number is equal to the sum of its positive, proper divisors.
|
| 2384 |
+
|
| 2385 |
+
Examples
|
| 2386 |
+
========
|
| 2387 |
+
|
| 2388 |
+
>>> from sympy.functions.combinatorial.numbers import divisor_sigma
|
| 2389 |
+
>>> from sympy.ntheory.factor_ import is_perfect, divisors
|
| 2390 |
+
>>> is_perfect(20)
|
| 2391 |
+
False
|
| 2392 |
+
>>> is_perfect(6)
|
| 2393 |
+
True
|
| 2394 |
+
>>> 6 == divisor_sigma(6) - 6 == sum(divisors(6)[:-1])
|
| 2395 |
+
True
|
| 2396 |
+
|
| 2397 |
+
References
|
| 2398 |
+
==========
|
| 2399 |
+
|
| 2400 |
+
.. [1] https://mathworld.wolfram.com/PerfectNumber.html
|
| 2401 |
+
.. [2] https://en.wikipedia.org/wiki/Perfect_number
|
| 2402 |
+
|
| 2403 |
+
"""
|
| 2404 |
+
n = as_int(n)
|
| 2405 |
+
if n < 1:
|
| 2406 |
+
return False
|
| 2407 |
+
if n % 2 == 0:
|
| 2408 |
+
m = (n.bit_length() + 1) >> 1
|
| 2409 |
+
if (1 << (m - 1)) * ((1 << m) - 1) != n:
|
| 2410 |
+
# Even perfect numbers must be of the form `2^{m-1}(2^m-1)`
|
| 2411 |
+
return False
|
| 2412 |
+
return m in MERSENNE_PRIME_EXPONENTS or is_mersenne_prime(2**m - 1)
|
| 2413 |
+
|
| 2414 |
+
# n is an odd integer
|
| 2415 |
+
if n < 10**2000: # https://www.lirmm.fr/~ochem/opn/
|
| 2416 |
+
return False
|
| 2417 |
+
if n % 105 == 0: # not divis by 105
|
| 2418 |
+
return False
|
| 2419 |
+
if all(n % m != r for m, r in [(12, 1), (468, 117), (324, 81)]):
|
| 2420 |
+
return False
|
| 2421 |
+
# there are many criteria that the factor structure of n
|
| 2422 |
+
# must meet; since we will have to factor it to test the
|
| 2423 |
+
# structure we will have the factors and can then check
|
| 2424 |
+
# to see whether it is a perfect number or not. So we
|
| 2425 |
+
# skip the structure checks and go straight to the final
|
| 2426 |
+
# test below.
|
| 2427 |
+
result = abundance(n) == 0
|
| 2428 |
+
if result:
|
| 2429 |
+
raise ValueError(filldedent('''In 1888, Sylvester stated: "
|
| 2430 |
+
...a prolonged meditation on the subject has satisfied
|
| 2431 |
+
me that the existence of any one such [odd perfect number]
|
| 2432 |
+
-- its escape, so to say, from the complex web of conditions
|
| 2433 |
+
which hem it in on all sides -- would be little short of a
|
| 2434 |
+
miracle." I guess SymPy just found that miracle and it
|
| 2435 |
+
factors like this: %s''' % factorint(n)))
|
| 2436 |
+
return result
|
| 2437 |
+
|
| 2438 |
+
|
| 2439 |
+
def abundance(n):
|
| 2440 |
+
"""Returns the difference between the sum of the positive
|
| 2441 |
+
proper divisors of a number and the number.
|
| 2442 |
+
|
| 2443 |
+
Examples
|
| 2444 |
+
========
|
| 2445 |
+
|
| 2446 |
+
>>> from sympy.ntheory import abundance, is_perfect, is_abundant
|
| 2447 |
+
>>> abundance(6)
|
| 2448 |
+
0
|
| 2449 |
+
>>> is_perfect(6)
|
| 2450 |
+
True
|
| 2451 |
+
>>> abundance(10)
|
| 2452 |
+
-2
|
| 2453 |
+
>>> is_abundant(10)
|
| 2454 |
+
False
|
| 2455 |
+
"""
|
| 2456 |
+
return _divisor_sigma(n) - 2 * n
|
| 2457 |
+
|
| 2458 |
+
|
| 2459 |
+
def is_abundant(n):
|
| 2460 |
+
"""Returns True if ``n`` is an abundant number, else False.
|
| 2461 |
+
|
| 2462 |
+
A abundant number is smaller than the sum of its positive proper divisors.
|
| 2463 |
+
|
| 2464 |
+
Examples
|
| 2465 |
+
========
|
| 2466 |
+
|
| 2467 |
+
>>> from sympy.ntheory.factor_ import is_abundant
|
| 2468 |
+
>>> is_abundant(20)
|
| 2469 |
+
True
|
| 2470 |
+
>>> is_abundant(15)
|
| 2471 |
+
False
|
| 2472 |
+
|
| 2473 |
+
References
|
| 2474 |
+
==========
|
| 2475 |
+
|
| 2476 |
+
.. [1] https://mathworld.wolfram.com/AbundantNumber.html
|
| 2477 |
+
|
| 2478 |
+
"""
|
| 2479 |
+
n = as_int(n)
|
| 2480 |
+
if is_perfect(n):
|
| 2481 |
+
return False
|
| 2482 |
+
return n % 6 == 0 or bool(abundance(n) > 0)
|
| 2483 |
+
|
| 2484 |
+
|
| 2485 |
+
def is_deficient(n):
|
| 2486 |
+
"""Returns True if ``n`` is a deficient number, else False.
|
| 2487 |
+
|
| 2488 |
+
A deficient number is greater than the sum of its positive proper divisors.
|
| 2489 |
+
|
| 2490 |
+
Examples
|
| 2491 |
+
========
|
| 2492 |
+
|
| 2493 |
+
>>> from sympy.ntheory.factor_ import is_deficient
|
| 2494 |
+
>>> is_deficient(20)
|
| 2495 |
+
False
|
| 2496 |
+
>>> is_deficient(15)
|
| 2497 |
+
True
|
| 2498 |
+
|
| 2499 |
+
References
|
| 2500 |
+
==========
|
| 2501 |
+
|
| 2502 |
+
.. [1] https://mathworld.wolfram.com/DeficientNumber.html
|
| 2503 |
+
|
| 2504 |
+
"""
|
| 2505 |
+
n = as_int(n)
|
| 2506 |
+
if is_perfect(n):
|
| 2507 |
+
return False
|
| 2508 |
+
return bool(abundance(n) < 0)
|
| 2509 |
+
|
| 2510 |
+
|
| 2511 |
+
def is_amicable(m, n):
|
| 2512 |
+
"""Returns True if the numbers `m` and `n` are "amicable", else False.
|
| 2513 |
+
|
| 2514 |
+
Amicable numbers are two different numbers so related that the sum
|
| 2515 |
+
of the proper divisors of each is equal to that of the other.
|
| 2516 |
+
|
| 2517 |
+
Examples
|
| 2518 |
+
========
|
| 2519 |
+
|
| 2520 |
+
>>> from sympy.functions.combinatorial.numbers import divisor_sigma
|
| 2521 |
+
>>> from sympy.ntheory.factor_ import is_amicable
|
| 2522 |
+
>>> is_amicable(220, 284)
|
| 2523 |
+
True
|
| 2524 |
+
>>> divisor_sigma(220) == divisor_sigma(284)
|
| 2525 |
+
True
|
| 2526 |
+
|
| 2527 |
+
References
|
| 2528 |
+
==========
|
| 2529 |
+
|
| 2530 |
+
.. [1] https://en.wikipedia.org/wiki/Amicable_numbers
|
| 2531 |
+
|
| 2532 |
+
"""
|
| 2533 |
+
return m != n and m + n == _divisor_sigma(m) == _divisor_sigma(n)
|
| 2534 |
+
|
| 2535 |
+
|
| 2536 |
+
def is_carmichael(n):
|
| 2537 |
+
""" Returns True if the numbers `n` is Carmichael number, else False.
|
| 2538 |
+
|
| 2539 |
+
Parameters
|
| 2540 |
+
==========
|
| 2541 |
+
|
| 2542 |
+
n : Integer
|
| 2543 |
+
|
| 2544 |
+
References
|
| 2545 |
+
==========
|
| 2546 |
+
|
| 2547 |
+
.. [1] https://en.wikipedia.org/wiki/Carmichael_number
|
| 2548 |
+
.. [2] https://oeis.org/A002997
|
| 2549 |
+
|
| 2550 |
+
"""
|
| 2551 |
+
if n < 561:
|
| 2552 |
+
return False
|
| 2553 |
+
return n % 2 and not isprime(n) and \
|
| 2554 |
+
all(e == 1 and (n - 1) % (p - 1) == 0 for p, e in factorint(n).items())
|
| 2555 |
+
|
| 2556 |
+
|
| 2557 |
+
def find_carmichael_numbers_in_range(x, y):
|
| 2558 |
+
""" Returns a list of the number of Carmichael in the range
|
| 2559 |
+
|
| 2560 |
+
See Also
|
| 2561 |
+
========
|
| 2562 |
+
|
| 2563 |
+
is_carmichael
|
| 2564 |
+
|
| 2565 |
+
"""
|
| 2566 |
+
if 0 <= x <= y:
|
| 2567 |
+
if x % 2 == 0:
|
| 2568 |
+
return [i for i in range(x + 1, y, 2) if is_carmichael(i)]
|
| 2569 |
+
else:
|
| 2570 |
+
return [i for i in range(x, y, 2) if is_carmichael(i)]
|
| 2571 |
+
else:
|
| 2572 |
+
raise ValueError('The provided range is not valid. x and y must be non-negative integers and x <= y')
|
| 2573 |
+
|
| 2574 |
+
|
| 2575 |
+
def find_first_n_carmichaels(n):
|
| 2576 |
+
""" Returns the first n Carmichael numbers.
|
| 2577 |
+
|
| 2578 |
+
Parameters
|
| 2579 |
+
==========
|
| 2580 |
+
|
| 2581 |
+
n : Integer
|
| 2582 |
+
|
| 2583 |
+
See Also
|
| 2584 |
+
========
|
| 2585 |
+
|
| 2586 |
+
is_carmichael
|
| 2587 |
+
|
| 2588 |
+
"""
|
| 2589 |
+
i = 561
|
| 2590 |
+
carmichaels = []
|
| 2591 |
+
|
| 2592 |
+
while len(carmichaels) < n:
|
| 2593 |
+
if is_carmichael(i):
|
| 2594 |
+
carmichaels.append(i)
|
| 2595 |
+
i += 2
|
| 2596 |
+
|
| 2597 |
+
return carmichaels
|
| 2598 |
+
|
| 2599 |
+
|
| 2600 |
+
def dra(n, b):
|
| 2601 |
+
"""
|
| 2602 |
+
Returns the additive digital root of a natural number ``n`` in base ``b``
|
| 2603 |
+
which is a single digit value obtained by an iterative process of summing
|
| 2604 |
+
digits, on each iteration using the result from the previous iteration to
|
| 2605 |
+
compute a digit sum.
|
| 2606 |
+
|
| 2607 |
+
Examples
|
| 2608 |
+
========
|
| 2609 |
+
|
| 2610 |
+
>>> from sympy.ntheory.factor_ import dra
|
| 2611 |
+
>>> dra(3110, 12)
|
| 2612 |
+
8
|
| 2613 |
+
|
| 2614 |
+
References
|
| 2615 |
+
==========
|
| 2616 |
+
|
| 2617 |
+
.. [1] https://en.wikipedia.org/wiki/Digital_root
|
| 2618 |
+
|
| 2619 |
+
"""
|
| 2620 |
+
|
| 2621 |
+
num = abs(as_int(n))
|
| 2622 |
+
b = as_int(b)
|
| 2623 |
+
if b <= 1:
|
| 2624 |
+
raise ValueError("Base should be an integer greater than 1")
|
| 2625 |
+
|
| 2626 |
+
if num == 0:
|
| 2627 |
+
return 0
|
| 2628 |
+
|
| 2629 |
+
return (1 + (num - 1) % (b - 1))
|
| 2630 |
+
|
| 2631 |
+
|
| 2632 |
+
def drm(n, b):
|
| 2633 |
+
"""
|
| 2634 |
+
Returns the multiplicative digital root of a natural number ``n`` in a given
|
| 2635 |
+
base ``b`` which is a single digit value obtained by an iterative process of
|
| 2636 |
+
multiplying digits, on each iteration using the result from the previous
|
| 2637 |
+
iteration to compute the digit multiplication.
|
| 2638 |
+
|
| 2639 |
+
Examples
|
| 2640 |
+
========
|
| 2641 |
+
|
| 2642 |
+
>>> from sympy.ntheory.factor_ import drm
|
| 2643 |
+
>>> drm(9876, 10)
|
| 2644 |
+
0
|
| 2645 |
+
|
| 2646 |
+
>>> drm(49, 10)
|
| 2647 |
+
8
|
| 2648 |
+
|
| 2649 |
+
References
|
| 2650 |
+
==========
|
| 2651 |
+
|
| 2652 |
+
.. [1] https://mathworld.wolfram.com/MultiplicativeDigitalRoot.html
|
| 2653 |
+
|
| 2654 |
+
"""
|
| 2655 |
+
|
| 2656 |
+
n = abs(as_int(n))
|
| 2657 |
+
b = as_int(b)
|
| 2658 |
+
if b <= 1:
|
| 2659 |
+
raise ValueError("Base should be an integer greater than 1")
|
| 2660 |
+
while n > b:
|
| 2661 |
+
mul = 1
|
| 2662 |
+
while n > 1:
|
| 2663 |
+
n, r = divmod(n, b)
|
| 2664 |
+
if r == 0:
|
| 2665 |
+
return 0
|
| 2666 |
+
mul *= r
|
| 2667 |
+
n = mul
|
| 2668 |
+
return n
|
infer_4_47_1/lib/python3.10/site-packages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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from math import prod
|
| 2 |
+
|
| 3 |
+
from sympy.external.gmpy import gcd, gcdext
|
| 4 |
+
from sympy.ntheory.primetest import isprime
|
| 5 |
+
from sympy.polys.domains import ZZ
|
| 6 |
+
from sympy.polys.galoistools import gf_crt, gf_crt1, gf_crt2
|
| 7 |
+
from sympy.utilities.misc import as_int
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def symmetric_residue(a, m):
|
| 11 |
+
"""Return the residual mod m such that it is within half of the modulus.
|
| 12 |
+
|
| 13 |
+
>>> from sympy.ntheory.modular import symmetric_residue
|
| 14 |
+
>>> symmetric_residue(1, 6)
|
| 15 |
+
1
|
| 16 |
+
>>> symmetric_residue(4, 6)
|
| 17 |
+
-2
|
| 18 |
+
"""
|
| 19 |
+
if a <= m // 2:
|
| 20 |
+
return a
|
| 21 |
+
return a - m
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def crt(m, v, symmetric=False, check=True):
|
| 25 |
+
r"""Chinese Remainder Theorem.
|
| 26 |
+
|
| 27 |
+
The moduli in m are assumed to be pairwise coprime. The output
|
| 28 |
+
is then an integer f, such that f = v_i mod m_i for each pair out
|
| 29 |
+
of v and m. If ``symmetric`` is False a positive integer will be
|
| 30 |
+
returned, else \|f\| will be less than or equal to the LCM of the
|
| 31 |
+
moduli, and thus f may be negative.
|
| 32 |
+
|
| 33 |
+
If the moduli are not co-prime the correct result will be returned
|
| 34 |
+
if/when the test of the result is found to be incorrect. This result
|
| 35 |
+
will be None if there is no solution.
|
| 36 |
+
|
| 37 |
+
The keyword ``check`` can be set to False if it is known that the moduli
|
| 38 |
+
are coprime.
|
| 39 |
+
|
| 40 |
+
Examples
|
| 41 |
+
========
|
| 42 |
+
|
| 43 |
+
As an example consider a set of residues ``U = [49, 76, 65]``
|
| 44 |
+
and a set of moduli ``M = [99, 97, 95]``. Then we have::
|
| 45 |
+
|
| 46 |
+
>>> from sympy.ntheory.modular import crt
|
| 47 |
+
|
| 48 |
+
>>> crt([99, 97, 95], [49, 76, 65])
|
| 49 |
+
(639985, 912285)
|
| 50 |
+
|
| 51 |
+
This is the correct result because::
|
| 52 |
+
|
| 53 |
+
>>> [639985 % m for m in [99, 97, 95]]
|
| 54 |
+
[49, 76, 65]
|
| 55 |
+
|
| 56 |
+
If the moduli are not co-prime, you may receive an incorrect result
|
| 57 |
+
if you use ``check=False``:
|
| 58 |
+
|
| 59 |
+
>>> crt([12, 6, 17], [3, 4, 2], check=False)
|
| 60 |
+
(954, 1224)
|
| 61 |
+
>>> [954 % m for m in [12, 6, 17]]
|
| 62 |
+
[6, 0, 2]
|
| 63 |
+
>>> crt([12, 6, 17], [3, 4, 2]) is None
|
| 64 |
+
True
|
| 65 |
+
>>> crt([3, 6], [2, 5])
|
| 66 |
+
(5, 6)
|
| 67 |
+
|
| 68 |
+
Note: the order of gf_crt's arguments is reversed relative to crt,
|
| 69 |
+
and that solve_congruence takes residue, modulus pairs.
|
| 70 |
+
|
| 71 |
+
Programmer's note: rather than checking that all pairs of moduli share
|
| 72 |
+
no GCD (an O(n**2) test) and rather than factoring all moduli and seeing
|
| 73 |
+
that there is no factor in common, a check that the result gives the
|
| 74 |
+
indicated residuals is performed -- an O(n) operation.
|
| 75 |
+
|
| 76 |
+
See Also
|
| 77 |
+
========
|
| 78 |
+
|
| 79 |
+
solve_congruence
|
| 80 |
+
sympy.polys.galoistools.gf_crt : low level crt routine used by this routine
|
| 81 |
+
"""
|
| 82 |
+
if check:
|
| 83 |
+
m = list(map(as_int, m))
|
| 84 |
+
v = list(map(as_int, v))
|
| 85 |
+
|
| 86 |
+
result = gf_crt(v, m, ZZ)
|
| 87 |
+
mm = prod(m)
|
| 88 |
+
|
| 89 |
+
if check:
|
| 90 |
+
if not all(v % m == result % m for v, m in zip(v, m)):
|
| 91 |
+
result = solve_congruence(*list(zip(v, m)),
|
| 92 |
+
check=False, symmetric=symmetric)
|
| 93 |
+
if result is None:
|
| 94 |
+
return result
|
| 95 |
+
result, mm = result
|
| 96 |
+
|
| 97 |
+
if symmetric:
|
| 98 |
+
return int(symmetric_residue(result, mm)), int(mm)
|
| 99 |
+
return int(result), int(mm)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def crt1(m):
|
| 103 |
+
"""First part of Chinese Remainder Theorem, for multiple application.
|
| 104 |
+
|
| 105 |
+
Examples
|
| 106 |
+
========
|
| 107 |
+
|
| 108 |
+
>>> from sympy.ntheory.modular import crt, crt1, crt2
|
| 109 |
+
>>> m = [99, 97, 95]
|
| 110 |
+
>>> v = [49, 76, 65]
|
| 111 |
+
|
| 112 |
+
The following two codes have the same result.
|
| 113 |
+
|
| 114 |
+
>>> crt(m, v)
|
| 115 |
+
(639985, 912285)
|
| 116 |
+
|
| 117 |
+
>>> mm, e, s = crt1(m)
|
| 118 |
+
>>> crt2(m, v, mm, e, s)
|
| 119 |
+
(639985, 912285)
|
| 120 |
+
|
| 121 |
+
However, it is faster when we want to fix ``m`` and
|
| 122 |
+
compute for multiple ``v``, i.e. the following cases:
|
| 123 |
+
|
| 124 |
+
>>> mm, e, s = crt1(m)
|
| 125 |
+
>>> vs = [[52, 21, 37], [19, 46, 76]]
|
| 126 |
+
>>> for v in vs:
|
| 127 |
+
... print(crt2(m, v, mm, e, s))
|
| 128 |
+
(397042, 912285)
|
| 129 |
+
(803206, 912285)
|
| 130 |
+
|
| 131 |
+
See Also
|
| 132 |
+
========
|
| 133 |
+
|
| 134 |
+
sympy.polys.galoistools.gf_crt1 : low level crt routine used by this routine
|
| 135 |
+
sympy.ntheory.modular.crt
|
| 136 |
+
sympy.ntheory.modular.crt2
|
| 137 |
+
|
| 138 |
+
"""
|
| 139 |
+
|
| 140 |
+
return gf_crt1(m, ZZ)
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def crt2(m, v, mm, e, s, symmetric=False):
|
| 144 |
+
"""Second part of Chinese Remainder Theorem, for multiple application.
|
| 145 |
+
|
| 146 |
+
See ``crt1`` for usage.
|
| 147 |
+
|
| 148 |
+
Examples
|
| 149 |
+
========
|
| 150 |
+
|
| 151 |
+
>>> from sympy.ntheory.modular import crt1, crt2
|
| 152 |
+
>>> mm, e, s = crt1([18, 42, 6])
|
| 153 |
+
>>> crt2([18, 42, 6], [0, 0, 0], mm, e, s)
|
| 154 |
+
(0, 4536)
|
| 155 |
+
|
| 156 |
+
See Also
|
| 157 |
+
========
|
| 158 |
+
|
| 159 |
+
sympy.polys.galoistools.gf_crt2 : low level crt routine used by this routine
|
| 160 |
+
sympy.ntheory.modular.crt
|
| 161 |
+
sympy.ntheory.modular.crt1
|
| 162 |
+
|
| 163 |
+
"""
|
| 164 |
+
|
| 165 |
+
result = gf_crt2(v, m, mm, e, s, ZZ)
|
| 166 |
+
|
| 167 |
+
if symmetric:
|
| 168 |
+
return int(symmetric_residue(result, mm)), int(mm)
|
| 169 |
+
return int(result), int(mm)
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def solve_congruence(*remainder_modulus_pairs, **hint):
|
| 173 |
+
"""Compute the integer ``n`` that has the residual ``ai`` when it is
|
| 174 |
+
divided by ``mi`` where the ``ai`` and ``mi`` are given as pairs to
|
| 175 |
+
this function: ((a1, m1), (a2, m2), ...). If there is no solution,
|
| 176 |
+
return None. Otherwise return ``n`` and its modulus.
|
| 177 |
+
|
| 178 |
+
The ``mi`` values need not be co-prime. If it is known that the moduli are
|
| 179 |
+
not co-prime then the hint ``check`` can be set to False (default=True) and
|
| 180 |
+
the check for a quicker solution via crt() (valid when the moduli are
|
| 181 |
+
co-prime) will be skipped.
|
| 182 |
+
|
| 183 |
+
If the hint ``symmetric`` is True (default is False), the value of ``n``
|
| 184 |
+
will be within 1/2 of the modulus, possibly negative.
|
| 185 |
+
|
| 186 |
+
Examples
|
| 187 |
+
========
|
| 188 |
+
|
| 189 |
+
>>> from sympy.ntheory.modular import solve_congruence
|
| 190 |
+
|
| 191 |
+
What number is 2 mod 3, 3 mod 5 and 2 mod 7?
|
| 192 |
+
|
| 193 |
+
>>> solve_congruence((2, 3), (3, 5), (2, 7))
|
| 194 |
+
(23, 105)
|
| 195 |
+
>>> [23 % m for m in [3, 5, 7]]
|
| 196 |
+
[2, 3, 2]
|
| 197 |
+
|
| 198 |
+
If you prefer to work with all remainder in one list and
|
| 199 |
+
all moduli in another, send the arguments like this:
|
| 200 |
+
|
| 201 |
+
>>> solve_congruence(*zip((2, 3, 2), (3, 5, 7)))
|
| 202 |
+
(23, 105)
|
| 203 |
+
|
| 204 |
+
The moduli need not be co-prime; in this case there may or
|
| 205 |
+
may not be a solution:
|
| 206 |
+
|
| 207 |
+
>>> solve_congruence((2, 3), (4, 6)) is None
|
| 208 |
+
True
|
| 209 |
+
|
| 210 |
+
>>> solve_congruence((2, 3), (5, 6))
|
| 211 |
+
(5, 6)
|
| 212 |
+
|
| 213 |
+
The symmetric flag will make the result be within 1/2 of the modulus:
|
| 214 |
+
|
| 215 |
+
>>> solve_congruence((2, 3), (5, 6), symmetric=True)
|
| 216 |
+
(-1, 6)
|
| 217 |
+
|
| 218 |
+
See Also
|
| 219 |
+
========
|
| 220 |
+
|
| 221 |
+
crt : high level routine implementing the Chinese Remainder Theorem
|
| 222 |
+
|
| 223 |
+
"""
|
| 224 |
+
def combine(c1, c2):
|
| 225 |
+
"""Return the tuple (a, m) which satisfies the requirement
|
| 226 |
+
that n = a + i*m satisfy n = a1 + j*m1 and n = a2 = k*m2.
|
| 227 |
+
|
| 228 |
+
References
|
| 229 |
+
==========
|
| 230 |
+
|
| 231 |
+
.. [1] https://en.wikipedia.org/wiki/Method_of_successive_substitution
|
| 232 |
+
"""
|
| 233 |
+
a1, m1 = c1
|
| 234 |
+
a2, m2 = c2
|
| 235 |
+
a, b, c = m1, a2 - a1, m2
|
| 236 |
+
g = gcd(a, b, c)
|
| 237 |
+
a, b, c = [i//g for i in [a, b, c]]
|
| 238 |
+
if a != 1:
|
| 239 |
+
g, inv_a, _ = gcdext(a, c)
|
| 240 |
+
if g != 1:
|
| 241 |
+
return None
|
| 242 |
+
b *= inv_a
|
| 243 |
+
a, m = a1 + m1*b, m1*c
|
| 244 |
+
return a, m
|
| 245 |
+
|
| 246 |
+
rm = remainder_modulus_pairs
|
| 247 |
+
symmetric = hint.get('symmetric', False)
|
| 248 |
+
|
| 249 |
+
if hint.get('check', True):
|
| 250 |
+
rm = [(as_int(r), as_int(m)) for r, m in rm]
|
| 251 |
+
|
| 252 |
+
# ignore redundant pairs but raise an error otherwise; also
|
| 253 |
+
# make sure that a unique set of bases is sent to gf_crt if
|
| 254 |
+
# they are all prime.
|
| 255 |
+
#
|
| 256 |
+
# The routine will work out less-trivial violations and
|
| 257 |
+
# return None, e.g. for the pairs (1,3) and (14,42) there
|
| 258 |
+
# is no answer because 14 mod 42 (having a gcd of 14) implies
|
| 259 |
+
# (14/2) mod (42/2), (14/7) mod (42/7) and (14/14) mod (42/14)
|
| 260 |
+
# which, being 0 mod 3, is inconsistent with 1 mod 3. But to
|
| 261 |
+
# preprocess the input beyond checking of another pair with 42
|
| 262 |
+
# or 3 as the modulus (for this example) is not necessary.
|
| 263 |
+
uniq = {}
|
| 264 |
+
for r, m in rm:
|
| 265 |
+
r %= m
|
| 266 |
+
if m in uniq:
|
| 267 |
+
if r != uniq[m]:
|
| 268 |
+
return None
|
| 269 |
+
continue
|
| 270 |
+
uniq[m] = r
|
| 271 |
+
rm = [(r, m) for m, r in uniq.items()]
|
| 272 |
+
del uniq
|
| 273 |
+
|
| 274 |
+
# if the moduli are co-prime, the crt will be significantly faster;
|
| 275 |
+
# checking all pairs for being co-prime gets to be slow but a prime
|
| 276 |
+
# test is a good trade-off
|
| 277 |
+
if all(isprime(m) for r, m in rm):
|
| 278 |
+
r, m = list(zip(*rm))
|
| 279 |
+
return crt(m, r, symmetric=symmetric, check=False)
|
| 280 |
+
|
| 281 |
+
rv = (0, 1)
|
| 282 |
+
for rmi in rm:
|
| 283 |
+
rv = combine(rv, rmi)
|
| 284 |
+
if rv is None:
|
| 285 |
+
break
|
| 286 |
+
n, m = rv
|
| 287 |
+
n = n % m
|
| 288 |
+
else:
|
| 289 |
+
if symmetric:
|
| 290 |
+
return symmetric_residue(n, m), m
|
| 291 |
+
return n, m
|
infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/multinomial.py
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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utilities.misc import as_int
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
def binomial_coefficients(n):
|
| 5 |
+
"""Return a dictionary containing pairs :math:`{(k1,k2) : C_kn}` where
|
| 6 |
+
:math:`C_kn` are binomial coefficients and :math:`n=k1+k2`.
|
| 7 |
+
|
| 8 |
+
Examples
|
| 9 |
+
========
|
| 10 |
+
|
| 11 |
+
>>> from sympy.ntheory import binomial_coefficients
|
| 12 |
+
>>> binomial_coefficients(9)
|
| 13 |
+
{(0, 9): 1, (1, 8): 9, (2, 7): 36, (3, 6): 84,
|
| 14 |
+
(4, 5): 126, (5, 4): 126, (6, 3): 84, (7, 2): 36, (8, 1): 9, (9, 0): 1}
|
| 15 |
+
|
| 16 |
+
See Also
|
| 17 |
+
========
|
| 18 |
+
|
| 19 |
+
binomial_coefficients_list, multinomial_coefficients
|
| 20 |
+
"""
|
| 21 |
+
n = as_int(n)
|
| 22 |
+
d = {(0, n): 1, (n, 0): 1}
|
| 23 |
+
a = 1
|
| 24 |
+
for k in range(1, n//2 + 1):
|
| 25 |
+
a = (a * (n - k + 1))//k
|
| 26 |
+
d[k, n - k] = d[n - k, k] = a
|
| 27 |
+
return d
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def binomial_coefficients_list(n):
|
| 31 |
+
""" Return a list of binomial coefficients as rows of the Pascal's
|
| 32 |
+
triangle.
|
| 33 |
+
|
| 34 |
+
Examples
|
| 35 |
+
========
|
| 36 |
+
|
| 37 |
+
>>> from sympy.ntheory import binomial_coefficients_list
|
| 38 |
+
>>> binomial_coefficients_list(9)
|
| 39 |
+
[1, 9, 36, 84, 126, 126, 84, 36, 9, 1]
|
| 40 |
+
|
| 41 |
+
See Also
|
| 42 |
+
========
|
| 43 |
+
|
| 44 |
+
binomial_coefficients, multinomial_coefficients
|
| 45 |
+
"""
|
| 46 |
+
n = as_int(n)
|
| 47 |
+
d = [1] * (n + 1)
|
| 48 |
+
a = 1
|
| 49 |
+
for k in range(1, n//2 + 1):
|
| 50 |
+
a = (a * (n - k + 1))//k
|
| 51 |
+
d[k] = d[n - k] = a
|
| 52 |
+
return d
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def multinomial_coefficients(m, n):
|
| 56 |
+
r"""Return a dictionary containing pairs ``{(k1,k2,..,km) : C_kn}``
|
| 57 |
+
where ``C_kn`` are multinomial coefficients such that
|
| 58 |
+
``n=k1+k2+..+km``.
|
| 59 |
+
|
| 60 |
+
Examples
|
| 61 |
+
========
|
| 62 |
+
|
| 63 |
+
>>> from sympy.ntheory import multinomial_coefficients
|
| 64 |
+
>>> multinomial_coefficients(2, 5) # indirect doctest
|
| 65 |
+
{(0, 5): 1, (1, 4): 5, (2, 3): 10, (3, 2): 10, (4, 1): 5, (5, 0): 1}
|
| 66 |
+
|
| 67 |
+
Notes
|
| 68 |
+
=====
|
| 69 |
+
|
| 70 |
+
The algorithm is based on the following result:
|
| 71 |
+
|
| 72 |
+
.. math::
|
| 73 |
+
\binom{n}{k_1, \ldots, k_m} =
|
| 74 |
+
\frac{k_1 + 1}{n - k_1} \sum_{i=2}^m \binom{n}{k_1 + 1, \ldots, k_i - 1, \ldots}
|
| 75 |
+
|
| 76 |
+
Code contributed to Sage by Yann Laigle-Chapuy, copied with permission
|
| 77 |
+
of the author.
|
| 78 |
+
|
| 79 |
+
See Also
|
| 80 |
+
========
|
| 81 |
+
|
| 82 |
+
binomial_coefficients_list, binomial_coefficients
|
| 83 |
+
"""
|
| 84 |
+
m = as_int(m)
|
| 85 |
+
n = as_int(n)
|
| 86 |
+
if not m:
|
| 87 |
+
if n:
|
| 88 |
+
return {}
|
| 89 |
+
return {(): 1}
|
| 90 |
+
if m == 2:
|
| 91 |
+
return binomial_coefficients(n)
|
| 92 |
+
if m >= 2*n and n > 1:
|
| 93 |
+
return dict(multinomial_coefficients_iterator(m, n))
|
| 94 |
+
t = [n] + [0] * (m - 1)
|
| 95 |
+
r = {tuple(t): 1}
|
| 96 |
+
if n:
|
| 97 |
+
j = 0 # j will be the leftmost nonzero position
|
| 98 |
+
else:
|
| 99 |
+
j = m
|
| 100 |
+
# enumerate tuples in co-lex order
|
| 101 |
+
while j < m - 1:
|
| 102 |
+
# compute next tuple
|
| 103 |
+
tj = t[j]
|
| 104 |
+
if j:
|
| 105 |
+
t[j] = 0
|
| 106 |
+
t[0] = tj
|
| 107 |
+
if tj > 1:
|
| 108 |
+
t[j + 1] += 1
|
| 109 |
+
j = 0
|
| 110 |
+
start = 1
|
| 111 |
+
v = 0
|
| 112 |
+
else:
|
| 113 |
+
j += 1
|
| 114 |
+
start = j + 1
|
| 115 |
+
v = r[tuple(t)]
|
| 116 |
+
t[j] += 1
|
| 117 |
+
# compute the value
|
| 118 |
+
# NB: the initialization of v was done above
|
| 119 |
+
for k in range(start, m):
|
| 120 |
+
if t[k]:
|
| 121 |
+
t[k] -= 1
|
| 122 |
+
v += r[tuple(t)]
|
| 123 |
+
t[k] += 1
|
| 124 |
+
t[0] -= 1
|
| 125 |
+
r[tuple(t)] = (v * tj) // (n - t[0])
|
| 126 |
+
return r
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def multinomial_coefficients_iterator(m, n, _tuple=tuple):
|
| 130 |
+
"""multinomial coefficient iterator
|
| 131 |
+
|
| 132 |
+
This routine has been optimized for `m` large with respect to `n` by taking
|
| 133 |
+
advantage of the fact that when the monomial tuples `t` are stripped of
|
| 134 |
+
zeros, their coefficient is the same as that of the monomial tuples from
|
| 135 |
+
``multinomial_coefficients(n, n)``. Therefore, the latter coefficients are
|
| 136 |
+
precomputed to save memory and time.
|
| 137 |
+
|
| 138 |
+
>>> from sympy.ntheory.multinomial import multinomial_coefficients
|
| 139 |
+
>>> m53, m33 = multinomial_coefficients(5,3), multinomial_coefficients(3,3)
|
| 140 |
+
>>> m53[(0,0,0,1,2)] == m53[(0,0,1,0,2)] == m53[(1,0,2,0,0)] == m33[(0,1,2)]
|
| 141 |
+
True
|
| 142 |
+
|
| 143 |
+
Examples
|
| 144 |
+
========
|
| 145 |
+
|
| 146 |
+
>>> from sympy.ntheory.multinomial import multinomial_coefficients_iterator
|
| 147 |
+
>>> it = multinomial_coefficients_iterator(20,3)
|
| 148 |
+
>>> next(it)
|
| 149 |
+
((3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), 1)
|
| 150 |
+
"""
|
| 151 |
+
m = as_int(m)
|
| 152 |
+
n = as_int(n)
|
| 153 |
+
if m < 2*n or n == 1:
|
| 154 |
+
mc = multinomial_coefficients(m, n)
|
| 155 |
+
yield from mc.items()
|
| 156 |
+
else:
|
| 157 |
+
mc = multinomial_coefficients(n, n)
|
| 158 |
+
mc1 = {}
|
| 159 |
+
for k, v in mc.items():
|
| 160 |
+
mc1[_tuple(filter(None, k))] = v
|
| 161 |
+
mc = mc1
|
| 162 |
+
|
| 163 |
+
t = [n] + [0] * (m - 1)
|
| 164 |
+
t1 = _tuple(t)
|
| 165 |
+
b = _tuple(filter(None, t1))
|
| 166 |
+
yield (t1, mc[b])
|
| 167 |
+
if n:
|
| 168 |
+
j = 0 # j will be the leftmost nonzero position
|
| 169 |
+
else:
|
| 170 |
+
j = m
|
| 171 |
+
# enumerate tuples in co-lex order
|
| 172 |
+
while j < m - 1:
|
| 173 |
+
# compute next tuple
|
| 174 |
+
tj = t[j]
|
| 175 |
+
if j:
|
| 176 |
+
t[j] = 0
|
| 177 |
+
t[0] = tj
|
| 178 |
+
if tj > 1:
|
| 179 |
+
t[j + 1] += 1
|
| 180 |
+
j = 0
|
| 181 |
+
else:
|
| 182 |
+
j += 1
|
| 183 |
+
t[j] += 1
|
| 184 |
+
|
| 185 |
+
t[0] -= 1
|
| 186 |
+
t1 = _tuple(t)
|
| 187 |
+
b = _tuple(filter(None, t1))
|
| 188 |
+
yield (t1, mc[b])
|
infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/partitions_.py
ADDED
|
@@ -0,0 +1,278 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from mpmath.libmp import (fzero, from_int, from_rational,
|
| 2 |
+
fone, fhalf, bitcount, to_int, mpf_mul, mpf_div, mpf_sub,
|
| 3 |
+
mpf_add, mpf_sqrt, mpf_pi, mpf_cosh_sinh, mpf_cos, mpf_sin)
|
| 4 |
+
from sympy.external.gmpy import gcd, legendre, jacobi
|
| 5 |
+
from .residue_ntheory import _sqrt_mod_prime_power, is_quad_residue
|
| 6 |
+
from sympy.utilities.decorator import deprecated
|
| 7 |
+
from sympy.utilities.memoization import recurrence_memo
|
| 8 |
+
|
| 9 |
+
import math
|
| 10 |
+
from itertools import count
|
| 11 |
+
|
| 12 |
+
def _pre():
|
| 13 |
+
maxn = 10**5
|
| 14 |
+
global _factor
|
| 15 |
+
global _totient
|
| 16 |
+
_factor = [0]*maxn
|
| 17 |
+
_totient = [1]*maxn
|
| 18 |
+
lim = int(maxn**0.5) + 5
|
| 19 |
+
for i in range(2, lim):
|
| 20 |
+
if _factor[i] == 0:
|
| 21 |
+
for j in range(i*i, maxn, i):
|
| 22 |
+
if _factor[j] == 0:
|
| 23 |
+
_factor[j] = i
|
| 24 |
+
for i in range(2, maxn):
|
| 25 |
+
if _factor[i] == 0:
|
| 26 |
+
_factor[i] = i
|
| 27 |
+
_totient[i] = i-1
|
| 28 |
+
continue
|
| 29 |
+
x = _factor[i]
|
| 30 |
+
y = i//x
|
| 31 |
+
if y % x == 0:
|
| 32 |
+
_totient[i] = _totient[y]*x
|
| 33 |
+
else:
|
| 34 |
+
_totient[i] = _totient[y]*(x - 1)
|
| 35 |
+
|
| 36 |
+
def _a(n, k, prec):
|
| 37 |
+
""" Compute the inner sum in HRR formula [1]_
|
| 38 |
+
|
| 39 |
+
References
|
| 40 |
+
==========
|
| 41 |
+
|
| 42 |
+
.. [1] https://msp.org/pjm/1956/6-1/pjm-v6-n1-p18-p.pdf
|
| 43 |
+
|
| 44 |
+
"""
|
| 45 |
+
if k == 1:
|
| 46 |
+
return fone
|
| 47 |
+
|
| 48 |
+
k1 = k
|
| 49 |
+
e = 0
|
| 50 |
+
p = _factor[k]
|
| 51 |
+
while k1 % p == 0:
|
| 52 |
+
k1 //= p
|
| 53 |
+
e += 1
|
| 54 |
+
k2 = k//k1 # k2 = p^e
|
| 55 |
+
v = 1 - 24*n
|
| 56 |
+
pi = mpf_pi(prec)
|
| 57 |
+
|
| 58 |
+
if k1 == 1:
|
| 59 |
+
# k = p^e
|
| 60 |
+
if p == 2:
|
| 61 |
+
mod = 8*k
|
| 62 |
+
v = mod + v % mod
|
| 63 |
+
v = (v*pow(9, k - 1, mod)) % mod
|
| 64 |
+
m = _sqrt_mod_prime_power(v, 2, e + 3)[0]
|
| 65 |
+
arg = mpf_div(mpf_mul(
|
| 66 |
+
from_int(4*m), pi, prec), from_int(mod), prec)
|
| 67 |
+
return mpf_mul(mpf_mul(
|
| 68 |
+
from_int((-1)**e*jacobi(m - 1, m)),
|
| 69 |
+
mpf_sqrt(from_int(k), prec), prec),
|
| 70 |
+
mpf_sin(arg, prec), prec)
|
| 71 |
+
if p == 3:
|
| 72 |
+
mod = 3*k
|
| 73 |
+
v = mod + v % mod
|
| 74 |
+
if e > 1:
|
| 75 |
+
v = (v*pow(64, k//3 - 1, mod)) % mod
|
| 76 |
+
m = _sqrt_mod_prime_power(v, 3, e + 1)[0]
|
| 77 |
+
arg = mpf_div(mpf_mul(from_int(4*m), pi, prec),
|
| 78 |
+
from_int(mod), prec)
|
| 79 |
+
return mpf_mul(mpf_mul(
|
| 80 |
+
from_int(2*(-1)**(e + 1)*legendre(m, 3)),
|
| 81 |
+
mpf_sqrt(from_int(k//3), prec), prec),
|
| 82 |
+
mpf_sin(arg, prec), prec)
|
| 83 |
+
v = k + v % k
|
| 84 |
+
if v % p == 0:
|
| 85 |
+
if e == 1:
|
| 86 |
+
return mpf_mul(
|
| 87 |
+
from_int(jacobi(3, k)),
|
| 88 |
+
mpf_sqrt(from_int(k), prec), prec)
|
| 89 |
+
return fzero
|
| 90 |
+
if not is_quad_residue(v, p):
|
| 91 |
+
return fzero
|
| 92 |
+
_phi = p**(e - 1)*(p - 1)
|
| 93 |
+
v = (v*pow(576, _phi - 1, k))
|
| 94 |
+
m = _sqrt_mod_prime_power(v, p, e)[0]
|
| 95 |
+
arg = mpf_div(
|
| 96 |
+
mpf_mul(from_int(4*m), pi, prec),
|
| 97 |
+
from_int(k), prec)
|
| 98 |
+
return mpf_mul(mpf_mul(
|
| 99 |
+
from_int(2*jacobi(3, k)),
|
| 100 |
+
mpf_sqrt(from_int(k), prec), prec),
|
| 101 |
+
mpf_cos(arg, prec), prec)
|
| 102 |
+
|
| 103 |
+
if p != 2 or e >= 3:
|
| 104 |
+
d1, d2 = gcd(k1, 24), gcd(k2, 24)
|
| 105 |
+
e = 24//(d1*d2)
|
| 106 |
+
n1 = ((d2*e*n + (k2**2 - 1)//d1)*
|
| 107 |
+
pow(e*k2*k2*d2, _totient[k1] - 1, k1)) % k1
|
| 108 |
+
n2 = ((d1*e*n + (k1**2 - 1)//d2)*
|
| 109 |
+
pow(e*k1*k1*d1, _totient[k2] - 1, k2)) % k2
|
| 110 |
+
return mpf_mul(_a(n1, k1, prec), _a(n2, k2, prec), prec)
|
| 111 |
+
if e == 2:
|
| 112 |
+
n1 = ((8*n + 5)*pow(128, _totient[k1] - 1, k1)) % k1
|
| 113 |
+
n2 = (4 + ((n - 2 - (k1**2 - 1)//8)*(k1**2)) % 4) % 4
|
| 114 |
+
return mpf_mul(mpf_mul(
|
| 115 |
+
from_int(-1),
|
| 116 |
+
_a(n1, k1, prec), prec),
|
| 117 |
+
_a(n2, k2, prec))
|
| 118 |
+
n1 = ((8*n + 1)*pow(32, _totient[k1] - 1, k1)) % k1
|
| 119 |
+
n2 = (2 + (n - (k1**2 - 1)//8) % 2) % 2
|
| 120 |
+
return mpf_mul(_a(n1, k1, prec), _a(n2, k2, prec), prec)
|
| 121 |
+
|
| 122 |
+
def _d(n, j, prec, sq23pi, sqrt8):
|
| 123 |
+
"""
|
| 124 |
+
Compute the sinh term in the outer sum of the HRR formula.
|
| 125 |
+
The constants sqrt(2/3*pi) and sqrt(8) must be precomputed.
|
| 126 |
+
"""
|
| 127 |
+
j = from_int(j)
|
| 128 |
+
pi = mpf_pi(prec)
|
| 129 |
+
a = mpf_div(sq23pi, j, prec)
|
| 130 |
+
b = mpf_sub(from_int(n), from_rational(1, 24, prec), prec)
|
| 131 |
+
c = mpf_sqrt(b, prec)
|
| 132 |
+
ch, sh = mpf_cosh_sinh(mpf_mul(a, c), prec)
|
| 133 |
+
D = mpf_div(
|
| 134 |
+
mpf_sqrt(j, prec),
|
| 135 |
+
mpf_mul(mpf_mul(sqrt8, b), pi), prec)
|
| 136 |
+
E = mpf_sub(mpf_mul(a, ch), mpf_div(sh, c, prec), prec)
|
| 137 |
+
return mpf_mul(D, E)
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
@recurrence_memo([1, 1])
|
| 141 |
+
def _partition_rec(n: int, prev) -> int:
|
| 142 |
+
""" Calculate the partition function P(n)
|
| 143 |
+
|
| 144 |
+
Parameters
|
| 145 |
+
==========
|
| 146 |
+
|
| 147 |
+
n : int
|
| 148 |
+
nonnegative integer
|
| 149 |
+
|
| 150 |
+
"""
|
| 151 |
+
v = 0
|
| 152 |
+
penta = 0 # pentagonal number: 1, 5, 12, ...
|
| 153 |
+
for i in count():
|
| 154 |
+
penta += 3*i + 1
|
| 155 |
+
np = n - penta
|
| 156 |
+
if np < 0:
|
| 157 |
+
break
|
| 158 |
+
s = prev[np]
|
| 159 |
+
np -= i + 1
|
| 160 |
+
# np = n - gp where gp = generalized pentagonal: 2, 7, 15, ...
|
| 161 |
+
if 0 <= np:
|
| 162 |
+
s += prev[np]
|
| 163 |
+
v += -s if i % 2 else s
|
| 164 |
+
return v
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def _partition(n: int) -> int:
|
| 168 |
+
""" Calculate the partition function P(n)
|
| 169 |
+
|
| 170 |
+
Parameters
|
| 171 |
+
==========
|
| 172 |
+
|
| 173 |
+
n : int
|
| 174 |
+
|
| 175 |
+
"""
|
| 176 |
+
if n < 0:
|
| 177 |
+
return 0
|
| 178 |
+
if (n <= 200_000 and n - _partition_rec.cache_length() < 70 or
|
| 179 |
+
_partition_rec.cache_length() == 2 and n < 14_400):
|
| 180 |
+
# There will be 2*10**5 elements created here
|
| 181 |
+
# and n elements created by partition, so in case we
|
| 182 |
+
# are going to be working with small n, we just
|
| 183 |
+
# use partition to calculate (and cache) the values
|
| 184 |
+
# since lookup is used there while summation, using
|
| 185 |
+
# _factor and _totient, will be used below. But we
|
| 186 |
+
# only do so if n is relatively close to the length
|
| 187 |
+
# of the cache since doing 1 calculation here is about
|
| 188 |
+
# the same as adding 70 elements to the cache. In addition,
|
| 189 |
+
# the startup here costs about the same as calculating the first
|
| 190 |
+
# 14,400 values via partition, so we delay startup here unless n
|
| 191 |
+
# is smaller than that.
|
| 192 |
+
return _partition_rec(n)
|
| 193 |
+
if '_factor' not in globals():
|
| 194 |
+
_pre()
|
| 195 |
+
# Estimate number of bits in p(n). This formula could be tidied
|
| 196 |
+
pbits = int((
|
| 197 |
+
math.pi*(2*n/3.)**0.5 -
|
| 198 |
+
math.log(4*n))/math.log(10) + 1) * \
|
| 199 |
+
math.log2(10)
|
| 200 |
+
prec = p = int(pbits*1.1 + 100)
|
| 201 |
+
|
| 202 |
+
# find the number of terms needed so rounded sum will be accurate
|
| 203 |
+
# using Rademacher's bound M(n, N) for the remainder after a partial
|
| 204 |
+
# sum of N terms (https://arxiv.org/pdf/1205.5991.pdf, (1.8))
|
| 205 |
+
c1 = 44*math.pi**2/(225*math.sqrt(3))
|
| 206 |
+
c2 = math.pi*math.sqrt(2)/75
|
| 207 |
+
c3 = math.pi*math.sqrt(2/3)
|
| 208 |
+
def _M(n, N):
|
| 209 |
+
sqrt = math.sqrt
|
| 210 |
+
return c1/sqrt(N) + c2*sqrt(N/(n - 1))*math.sinh(c3*sqrt(n)/N)
|
| 211 |
+
big = max(9, math.ceil(n**0.5)) # should be too large (for n > 65, ceil should work)
|
| 212 |
+
assert _M(n, big) < 0.5 # else double big until too large
|
| 213 |
+
while big > 40 and _M(n, big) < 0.5:
|
| 214 |
+
big //= 2
|
| 215 |
+
small = big
|
| 216 |
+
big = small*2
|
| 217 |
+
while big - small > 1:
|
| 218 |
+
N = (big + small)//2
|
| 219 |
+
if (er := _M(n, N)) < 0.5:
|
| 220 |
+
big = N
|
| 221 |
+
elif er >= 0.5:
|
| 222 |
+
small = N
|
| 223 |
+
M = big # done with function M; now have value
|
| 224 |
+
|
| 225 |
+
# sanity check for expected size of answer
|
| 226 |
+
if M > 10**5: # i.e. M > maxn
|
| 227 |
+
raise ValueError("Input too big") # i.e. n > 149832547102
|
| 228 |
+
|
| 229 |
+
# calculate it
|
| 230 |
+
s = fzero
|
| 231 |
+
sq23pi = mpf_mul(mpf_sqrt(from_rational(2, 3, p), p), mpf_pi(p), p)
|
| 232 |
+
sqrt8 = mpf_sqrt(from_int(8), p)
|
| 233 |
+
for q in range(1, M):
|
| 234 |
+
a = _a(n, q, p)
|
| 235 |
+
d = _d(n, q, p, sq23pi, sqrt8)
|
| 236 |
+
s = mpf_add(s, mpf_mul(a, d), prec)
|
| 237 |
+
# On average, the terms decrease rapidly in magnitude.
|
| 238 |
+
# Dynamically reducing the precision greatly improves
|
| 239 |
+
# performance.
|
| 240 |
+
p = bitcount(abs(to_int(d))) + 50
|
| 241 |
+
return int(to_int(mpf_add(s, fhalf, prec)))
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
@deprecated("""\
|
| 245 |
+
The `sympy.ntheory.partitions_.npartitions` has been moved to `sympy.functions.combinatorial.numbers.partition`.""",
|
| 246 |
+
deprecated_since_version="1.13",
|
| 247 |
+
active_deprecations_target='deprecated-ntheory-symbolic-functions')
|
| 248 |
+
def npartitions(n, verbose=False):
|
| 249 |
+
"""
|
| 250 |
+
Calculate the partition function P(n), i.e. the number of ways that
|
| 251 |
+
n can be written as a sum of positive integers.
|
| 252 |
+
|
| 253 |
+
.. deprecated:: 1.13
|
| 254 |
+
|
| 255 |
+
The ``npartitions`` function is deprecated. Use :class:`sympy.functions.combinatorial.numbers.partition`
|
| 256 |
+
instead. See its documentation for more information. See
|
| 257 |
+
:ref:`deprecated-ntheory-symbolic-functions` for details.
|
| 258 |
+
|
| 259 |
+
P(n) is computed using the Hardy-Ramanujan-Rademacher formula [1]_.
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
The correctness of this implementation has been tested through $10^{10}$.
|
| 263 |
+
|
| 264 |
+
Examples
|
| 265 |
+
========
|
| 266 |
+
|
| 267 |
+
>>> from sympy.functions.combinatorial.numbers import partition
|
| 268 |
+
>>> partition(25)
|
| 269 |
+
1958
|
| 270 |
+
|
| 271 |
+
References
|
| 272 |
+
==========
|
| 273 |
+
|
| 274 |
+
.. [1] https://mathworld.wolfram.com/PartitionFunctionP.html
|
| 275 |
+
|
| 276 |
+
"""
|
| 277 |
+
from sympy.functions.combinatorial.numbers import partition as func_partition
|
| 278 |
+
return func_partition(n)
|
infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_bbp_pi.cpython-310.pyc
ADDED
|
Binary file (9.62 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_continued_fraction.cpython-310.pyc
ADDED
|
Binary file (4.39 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_ecm.cpython-310.pyc
ADDED
|
Binary file (2.07 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_generate.cpython-310.pyc
ADDED
|
Binary file (11.2 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_hypothesis.cpython-310.pyc
ADDED
|
Binary file (1.51 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_modular.cpython-310.pyc
ADDED
|
Binary file (1.88 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_multinomial.cpython-310.pyc
ADDED
|
Binary file (2.68 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_partitions.cpython-310.pyc
ADDED
|
Binary file (1.54 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_primetest.cpython-310.pyc
ADDED
|
Binary file (8.72 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_qs.cpython-310.pyc
ADDED
|
Binary file (4.84 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/sympy/ntheory/tests/test_continued_fraction.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import itertools
|
| 2 |
+
from sympy.core import GoldenRatio as phi
|
| 3 |
+
from sympy.core.numbers import (Rational, pi)
|
| 4 |
+
from sympy.core.singleton import S
|
| 5 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
| 6 |
+
from sympy.ntheory.continued_fraction import \
|
| 7 |
+
(continued_fraction_periodic as cf_p,
|
| 8 |
+
continued_fraction_iterator as cf_i,
|
| 9 |
+
continued_fraction_convergents as cf_c,
|
| 10 |
+
continued_fraction_reduce as cf_r,
|
| 11 |
+
continued_fraction as cf)
|
| 12 |
+
from sympy.testing.pytest import raises
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def test_continued_fraction():
|
| 16 |
+
assert cf_p(1, 1, 10, 0) == cf_p(1, 1, 0, 1)
|
| 17 |
+
assert cf_p(1, -1, 10, 1) == cf_p(-1, 1, 10, -1)
|
| 18 |
+
t = sqrt(2)
|
| 19 |
+
assert cf((1 + t)*(1 - t)) == cf(-1)
|
| 20 |
+
for n in [0, 2, Rational(2, 3), sqrt(2), 3*sqrt(2), 1 + 2*sqrt(3)/5,
|
| 21 |
+
(2 - 3*sqrt(5))/7, 1 + sqrt(2), (-5 + sqrt(17))/4]:
|
| 22 |
+
assert (cf_r(cf(n)) - n).expand() == 0
|
| 23 |
+
assert (cf_r(cf(-n)) + n).expand() == 0
|
| 24 |
+
raises(ValueError, lambda: cf(sqrt(2 + sqrt(3))))
|
| 25 |
+
raises(ValueError, lambda: cf(sqrt(2) + sqrt(3)))
|
| 26 |
+
raises(ValueError, lambda: cf(pi))
|
| 27 |
+
raises(ValueError, lambda: cf(.1))
|
| 28 |
+
|
| 29 |
+
raises(ValueError, lambda: cf_p(1, 0, 0))
|
| 30 |
+
raises(ValueError, lambda: cf_p(1, 1, -1))
|
| 31 |
+
assert cf_p(4, 3, 0) == [1, 3]
|
| 32 |
+
assert cf_p(0, 3, 5) == [0, 1, [2, 1, 12, 1, 2, 2]]
|
| 33 |
+
assert cf_p(1, 1, 0) == [1]
|
| 34 |
+
assert cf_p(3, 4, 0) == [0, 1, 3]
|
| 35 |
+
assert cf_p(4, 5, 0) == [0, 1, 4]
|
| 36 |
+
assert cf_p(5, 6, 0) == [0, 1, 5]
|
| 37 |
+
assert cf_p(11, 13, 0) == [0, 1, 5, 2]
|
| 38 |
+
assert cf_p(16, 19, 0) == [0, 1, 5, 3]
|
| 39 |
+
assert cf_p(27, 32, 0) == [0, 1, 5, 2, 2]
|
| 40 |
+
assert cf_p(1, 2, 5) == [[1]]
|
| 41 |
+
assert cf_p(0, 1, 2) == [1, [2]]
|
| 42 |
+
assert cf_p(6, 7, 49) == [1, 1, 6]
|
| 43 |
+
assert cf_p(3796, 1387, 0) == [2, 1, 2, 1, 4]
|
| 44 |
+
assert cf_p(3245, 10000) == [0, 3, 12, 4, 13]
|
| 45 |
+
assert cf_p(1932, 2568) == [0, 1, 3, 26, 2]
|
| 46 |
+
assert cf_p(6589, 2569) == [2, 1, 1, 3, 2, 1, 3, 1, 23]
|
| 47 |
+
|
| 48 |
+
def take(iterator, n=7):
|
| 49 |
+
return list(itertools.islice(iterator, n))
|
| 50 |
+
|
| 51 |
+
assert take(cf_i(phi)) == [1, 1, 1, 1, 1, 1, 1]
|
| 52 |
+
assert take(cf_i(pi)) == [3, 7, 15, 1, 292, 1, 1]
|
| 53 |
+
|
| 54 |
+
assert list(cf_i(Rational(17, 12))) == [1, 2, 2, 2]
|
| 55 |
+
assert list(cf_i(Rational(-17, 12))) == [-2, 1, 1, 2, 2]
|
| 56 |
+
|
| 57 |
+
assert list(cf_c([1, 6, 1, 8])) == [S.One, Rational(7, 6), Rational(8, 7), Rational(71, 62)]
|
| 58 |
+
assert list(cf_c([2])) == [S(2)]
|
| 59 |
+
assert list(cf_c([1, 1, 1, 1, 1, 1, 1])) == [S.One, S(2), Rational(3, 2), Rational(5, 3),
|
| 60 |
+
Rational(8, 5), Rational(13, 8), Rational(21, 13)]
|
| 61 |
+
assert list(cf_c([1, 6, Rational(-1, 2), 4])) == [S.One, Rational(7, 6), Rational(5, 4), Rational(3, 2)]
|
| 62 |
+
assert take(cf_c([[1]])) == [S.One, S(2), Rational(3, 2), Rational(5, 3), Rational(8, 5),
|
| 63 |
+
Rational(13, 8), Rational(21, 13)]
|
| 64 |
+
assert take(cf_c([1, [1, 2]])) == [S.One, S(2), Rational(5, 3), Rational(7, 4), Rational(19, 11),
|
| 65 |
+
Rational(26, 15), Rational(71, 41)]
|
| 66 |
+
|
| 67 |
+
cf_iter_e = (2 if i == 1 else i // 3 * 2 if i % 3 == 0 else 1 for i in itertools.count(1))
|
| 68 |
+
assert take(cf_c(cf_iter_e)) == [S(2), S(3), Rational(8, 3), Rational(11, 4), Rational(19, 7),
|
| 69 |
+
Rational(87, 32), Rational(106, 39)]
|
| 70 |
+
|
| 71 |
+
assert cf_r([1, 6, 1, 8]) == Rational(71, 62)
|
| 72 |
+
assert cf_r([3]) == S(3)
|
| 73 |
+
assert cf_r([-1, 5, 1, 4]) == Rational(-24, 29)
|
| 74 |
+
assert (cf_r([0, 1, 1, 7, [24, 8]]) - (sqrt(3) + 2)/7).expand() == 0
|
| 75 |
+
assert cf_r([1, 5, 9]) == Rational(55, 46)
|
| 76 |
+
assert (cf_r([[1]]) - (sqrt(5) + 1)/2).expand() == 0
|
| 77 |
+
assert cf_r([-3, 1, 1, [2]]) == -1 - sqrt(2)
|