11th grade-all tasks
2018-09-26-183735/2018-09-26-154656 / assignment / assignment1 / Assignment 1-final submission.ipynb
2151 viewsKernel: Python 3 (old Anaconda 3)
In [5]:
Out[5]:
['Roey Dvir']
החבילה SymPy
SymPy היא ספרייה למתמטיקה סימבולית המיועדת ל- Python. היא כתובה כולה רק ב-Python, כך שאין צורך בסיפריות נוספות כדי להשתמש בה. בכוונת מפתחי ה- Sympy לפתחה עד כדי מערכת המכילה את כל התכונות והיכולות של תוכנות CAS, ראשי תיבות של Computer Algebric System. המפתחים מנסים לשמור את הקוד פשוט ככל האפשר כדי ליצור חבילה קלה להבנה ושאפשר להרחיבה בקלות.
באופן בסיסי Sympy היא מחשבון סימבולי, אבל יתרונה בכך שאפשר להשתמש בה בתוכנית מחשב.
In [0]:
תרגיל 1
חשבו:
In [7]:
Out[7]:
Symbols
האוביקט הבסיסי ב- Sympy הוא ה- Symbol אוביקט זה מייצג משתנה מתמטי. יצירת אובייקט זה נעשיית באמצעות הפונקציה Symbol
In [8]:
Out[8]:
תרגיל 2
בעזרת הפונקציה symbols צרו את המשתנים ו- (החליפו את ה- ? בקוד המתאים)
In [9]:
Out[9]:
תרגיל 3
הגדירו את הפונקציה פונקציה זו מכונה פונקציית הפעמון.
את הפונקציה מגדירים כ- (exp(x
In [10]:
Out[10]:
גזירה של פונקציה
In [11]:
Out[11]:
In [12]:
Out[12]:
שרטוט גרף באמצעות sympy.plotting
In [0]:
In [13]:
Out[13]:
<sympy.plotting.plot.Plot at 0x7fd93dbeec50>
תרגיל 4
חשבו את הניגזרת השנייה של פונקציית "הפעמון"
ושרטטו גרף שלה (הניחו כי : ו- )
הערה: חשבו את הנגזרת ולאחר מכן הגדירו את ביטוי הניגזרת מחדש כאשר אתם מציבים ערכים לפרמטרים: .
הערה: חשבו את הנגזרת ולאחר מכן הגדירו את ביטוי הניגזרת מחדש כאשר אתם מציבים ערכים לפרמטרים: .
In [14]:
Out[14]:
<sympy.plotting.plot.Plot at 0x7fd93bae5f98>
הפונקציות simplify, subs,expand,evalf
In [15]:
Out[15]:
In [16]:
Out[16]:
In [17]:
Out[17]:
In [18]:
Out[18]:
In [19]:
Out[19]:
תרגיל 5
בעזרת הפונקציה help בדקו מה פעולת הפונקציה simplify.
מה עושה כל אחת מהפונקציות subs, evalf ו- expand
In [20]:
Out[20]:
Help on function simplify in module sympy.simplify.simplify:
simplify(expr, ratio=1.7, measure=<function count_ops at 0x7fd93e743620>, fu=False)
Simplifies the given expression.
Simplification is not a well defined term and the exact strategies
this function tries can change in the future versions of SymPy. If
your algorithm relies on "simplification" (whatever it is), try to
determine what you need exactly - is it powsimp()?, radsimp()?,
together()?, logcombine()?, or something else? And use this particular
function directly, because those are well defined and thus your algorithm
will be robust.
Nonetheless, especially for interactive use, or when you don't know
anything about the structure of the expression, simplify() tries to apply
intelligent heuristics to make the input expression "simpler". For
example:
>>> from sympy import simplify, cos, sin
>>> from sympy.abc import x, y
>>> a = (x + x**2)/(x*sin(y)**2 + x*cos(y)**2)
>>> a
(x**2 + x)/(x*sin(y)**2 + x*cos(y)**2)
>>> simplify(a)
x + 1
Note that we could have obtained the same result by using specific
simplification functions:
>>> from sympy import trigsimp, cancel
>>> trigsimp(a)
(x**2 + x)/x
>>> cancel(_)
x + 1
In some cases, applying :func:`simplify` may actually result in some more
complicated expression. The default ``ratio=1.7`` prevents more extreme
cases: if (result length)/(input length) > ratio, then input is returned
unmodified. The ``measure`` parameter lets you specify the function used
to determine how complex an expression is. The function should take a
single argument as an expression and return a number such that if
expression ``a`` is more complex than expression ``b``, then
``measure(a) > measure(b)``. The default measure function is
:func:`count_ops`, which returns the total number of operations in the
expression.
For example, if ``ratio=1``, ``simplify`` output can't be longer
than input.
::
>>> from sympy import sqrt, simplify, count_ops, oo
>>> root = 1/(sqrt(2)+3)
Since ``simplify(root)`` would result in a slightly longer expression,
root is returned unchanged instead::
>>> simplify(root, ratio=1) == root
True
If ``ratio=oo``, simplify will be applied anyway::
>>> count_ops(simplify(root, ratio=oo)) > count_ops(root)
True
Note that the shortest expression is not necessary the simplest, so
setting ``ratio`` to 1 may not be a good idea.
Heuristically, the default value ``ratio=1.7`` seems like a reasonable
choice.
You can easily define your own measure function based on what you feel
should represent the "size" or "complexity" of the input expression. Note
that some choices, such as ``lambda expr: len(str(expr))`` may appear to be
good metrics, but have other problems (in this case, the measure function
may slow down simplify too much for very large expressions). If you don't
know what a good metric would be, the default, ``count_ops``, is a good
one.
For example:
>>> from sympy import symbols, log
>>> a, b = symbols('a b', positive=True)
>>> g = log(a) + log(b) + log(a)*log(1/b)
>>> h = simplify(g)
>>> h
log(a*b**(-log(a) + 1))
>>> count_ops(g)
8
>>> count_ops(h)
5
So you can see that ``h`` is simpler than ``g`` using the count_ops metric.
However, we may not like how ``simplify`` (in this case, using
``logcombine``) has created the ``b**(log(1/a) + 1)`` term. A simple way
to reduce this would be to give more weight to powers as operations in
``count_ops``. We can do this by using the ``visual=True`` option:
>>> print(count_ops(g, visual=True))
2*ADD + DIV + 4*LOG + MUL
>>> print(count_ops(h, visual=True))
2*LOG + MUL + POW + SUB
>>> from sympy import Symbol, S
>>> def my_measure(expr):
... POW = Symbol('POW')
... # Discourage powers by giving POW a weight of 10
... count = count_ops(expr, visual=True).subs(POW, 10)
... # Every other operation gets a weight of 1 (the default)
... count = count.replace(Symbol, type(S.One))
... return count
>>> my_measure(g)
8
>>> my_measure(h)
14
>>> 15./8 > 1.7 # 1.7 is the default ratio
True
>>> simplify(g, measure=my_measure)
-log(a)*log(b) + log(a) + log(b)
Note that because ``simplify()`` internally tries many different
simplification strategies and then compares them using the measure
function, we get a completely different result that is still different
from the input expression by doing this.
Help on module sympy.core.evalf in sympy.core:
NAME
sympy.core.evalf
DESCRIPTION
Adaptive numerical evaluation of SymPy expressions, using mpmath
for mathematical functions.
CLASSES
builtins.ArithmeticError(builtins.Exception)
PrecisionExhausted
builtins.object
EvalfMixin
class EvalfMixin(builtins.object)
| Mixin class adding evalf capabililty.
|
| Methods defined here:
|
| evalf(self, n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)
| Evaluate the given formula to an accuracy of n digits.
| Optional keyword arguments:
|
| subs=<dict>
| Substitute numerical values for symbols, e.g.
| subs={x:3, y:1+pi}. The substitutions must be given as a
| dictionary.
|
| maxn=<integer>
| Allow a maximum temporary working precision of maxn digits
| (default=100)
|
| chop=<bool>
| Replace tiny real or imaginary parts in subresults
| by exact zeros (default=False)
|
| strict=<bool>
| Raise PrecisionExhausted if any subresult fails to evaluate
| to full accuracy, given the available maxprec
| (default=False)
|
| quad=<str>
| Choose algorithm for numerical quadrature. By default,
| tanh-sinh quadrature is used. For oscillatory
| integrals on an infinite interval, try quad='osc'.
|
| verbose=<bool>
| Print debug information (default=False)
|
| n = evalf(self, n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False)
class PrecisionExhausted(builtins.ArithmeticError)
| Base class for arithmetic errors.
|
| Method resolution order:
| PrecisionExhausted
| builtins.ArithmeticError
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Data descriptors defined here:
|
| __weakref__
| list of weak references to the object (if defined)
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.ArithmeticError:
|
| __init__(self, /, *args, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __delattr__(self, name, /)
| Implement delattr(self, name).
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| helper for pickle
|
| __repr__(self, /)
| Return repr(self).
|
| __setattr__(self, name, value, /)
| Implement setattr(self, name, value).
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
FUNCTIONS
MPZ = mpz(...)
mpz() -> mpz(0)
If no argument is given, return mpz(0).
mpz(n) -> mpz
Return an 'mpz' object with a numeric value 'n' (truncating n
to its integer part if it's a Fraction, 'mpq', Decimal, float
or 'mpfr').
mpz(s[, base=0]):
Return an 'mpz' object from a string 's' made of digits in the
given base. If base=0, binary, octal, or hex Python strings
are recognized by leading 0b, 0o, or 0x characters, otherwise
the string is assumed to be decimal. Values for base can range
between 2 and 62.
N(x, n=15, **options)
Calls x.evalf(n, \*\*options).
Both .n() and N() are equivalent to .evalf(); use the one that you like better.
See also the docstring of .evalf() for information on the options.
Examples
========
>>> from sympy import Sum, oo, N
>>> from sympy.abc import k
>>> Sum(1/k**k, (k, 1, oo))
Sum(k**(-k), (k, 1, oo))
>>> N(_, 4)
1.291
add_terms(terms, prec, target_prec)
Helper for evalf_add. Adds a list of (mpfval, accuracy) terms.
Returns
-------
- None, None if there are no non-zero terms;
- terms[0] if there is only 1 term;
- scaled_zero if the sum of the terms produces a zero by cancellation
e.g. mpfs representing 1 and -1 would produce a scaled zero which need
special handling since they are not actually zero and they are purposely
malformed to ensure that they can't be used in anything but accuracy
calculations;
- a tuple that is scaled to target_prec that corresponds to the
sum of the terms.
The returned mpf tuple will be normalized to target_prec; the input
prec is used to define the working precision.
XXX explain why this is needed and why one can't just loop using mpf_add
as_mpmath(x, prec, options)
bitcount(n)
check_convergence(numer, denom, n)
Returns (h, g, p) where
-- h is:
> 0 for convergence of rate 1/factorial(n)**h
< 0 for divergence of rate factorial(n)**(-h)
= 0 for geometric or polynomial convergence or divergence
-- abs(g) is:
> 1 for geometric convergence of rate 1/h**n
< 1 for geometric divergence of rate h**n
= 1 for polynomial convergence or divergence
(g < 0 indicates an alternating series)
-- p is:
> 1 for polynomial convergence of rate 1/n**h
<= 1 for polynomial divergence of rate n**(-h)
check_target(expr, result, prec)
chop_parts(value, prec)
Chop off tiny real or complex parts.
complex_accuracy(result)
Returns relative accuracy of a complex number with given accuracies
for the real and imaginary parts. The relative accuracy is defined
in the complex norm sense as ||z|+|error|| / |z| where error
is equal to (real absolute error) + (imag absolute error)*i.
The full expression for the (logarithmic) error can be approximated
easily by using the max norm to approximate the complex norm.
In the worst case (re and im equal), this is wrong by a factor
sqrt(2), or by log2(sqrt(2)) = 0.5 bit.
do_integral(expr, prec, options)
evalf(x, prec, options)
evalf_abs(expr, prec, options)
evalf_add(v, prec, options)
evalf_atan(v, prec, options)
evalf_bernoulli(expr, prec, options)
evalf_ceiling(expr, prec, options)
evalf_floor(expr, prec, options)
evalf_im(expr, prec, options)
evalf_integral(expr, prec, options)
evalf_log(expr, prec, options)
evalf_mul(v, prec, options)
evalf_piecewise(expr, prec, options)
evalf_pow(v, prec, options)
evalf_prod(expr, prec, options)
evalf_re(expr, prec, options)
evalf_subs(prec, subs)
Change all Float entries in `subs` to have precision prec.
evalf_sum(expr, prec, options)
evalf_symbol(x, prec, options)
evalf_trig(v, prec, options)
This function handles sin and cos of complex arguments.
TODO: should also handle tan of complex arguments.
fastlog(x)
Fast approximation of log2(x) for an mpf value tuple x.
Notes: Calculated as exponent + width of mantissa. This is an
approximation for two reasons: 1) it gives the ceil(log2(abs(x)))
value and 2) it is too high by 1 in the case that x is an exact
power of 2. Although this is easy to remedy by testing to see if
the odd mpf mantissa is 1 (indicating that one was dealing with
an exact power of 2) that would decrease the speed and is not
necessary as this is only being used as an approximation for the
number of bits in x. The correct return value could be written as
"x[2] + (x[3] if x[1] != 1 else 0)".
Since mpf tuples always have an odd mantissa, no check is done
to see if the mantissa is a multiple of 2 (in which case the
result would be too large by 1).
Examples
========
>>> from sympy import log
>>> from sympy.core.evalf import fastlog, bitcount
>>> s, m, e = 0, 5, 1
>>> bc = bitcount(m)
>>> n = [1, -1][s]*m*2**e
>>> n, (log(n)/log(2)).evalf(2), fastlog((s, m, e, bc))
(10, 3.3, 4)
finalize_complex(re, im, prec)
from_man_exp = _mpmath_create(...)
_mpmath_create(...): helper function for mpmath.
get_abs(expr, prec, options)
get_complex_part(expr, no, prec, options)
no = 0 for real part, no = 1 for imaginary part
get_integer_part(expr, no, options, return_ints=False)
With no = 1, computes ceiling(expr)
With no = -1, computes floor(expr)
Note: this function either gives the exact result or signals failure.
hypsum(expr, n, start, prec)
Sum a rapidly convergent infinite hypergeometric series with
given general term, e.g. e = hypsum(1/factorial(n), n). The
quotient between successive terms must be a quotient of integer
polynomials.
iszero(mpf, scaled=False)
mpmath_bitcount = bit_length(...)
x.bit_length() -> int
Return the number of significant bits in the radix-2
representation of x. Note: mpz(0).bit_length() returns 0.
normalize = _mpmath_normalize(...)
_mpmath_normalize(...): helper function for mpmath.
pure_complex(v, or_real=False)
Return a and b if v matches a + I*b where b is not zero and
a and b are Numbers, else None. If `or_real` is True then 0 will
be returned for `b` if `v` is a real number.
>>> from sympy.core.evalf import pure_complex
>>> from sympy import sqrt, I, S
>>> a, b, surd = S(2), S(3), sqrt(2)
>>> pure_complex(a)
>>> pure_complex(a, or_real=True)
(2, 0)
>>> pure_complex(surd)
>>> pure_complex(a + b*I)
(2, 3)
>>> pure_complex(I)
(0, 1)
scaled_zero(mag, sign=1)
Return an mpf representing a power of two with magnitude ``mag``
and -1 for precision. Or, if ``mag`` is a scaled_zero tuple, then just
remove the sign from within the list that it was initially wrapped
in.
Examples
========
>>> from sympy.core.evalf import scaled_zero
>>> from sympy import Float
>>> z, p = scaled_zero(100)
>>> z, p
(([0], 1, 100, 1), -1)
>>> ok = scaled_zero(z)
>>> ok
(0, 1, 100, 1)
>>> Float(ok)
1.26765060022823e+30
>>> Float(ok, p)
0.e+30
>>> ok, p = scaled_zero(100, -1)
>>> Float(scaled_zero(ok), p)
-0.e+30
DATA
DEFAULT_MAXPREC = 333
INF = inf
LG10 = 3.3219280948873626
MINUS_INF = -inf
S = S
SYMPY_INTS = (<class 'int'>, <class 'mpz'>)
division = _Feature((2, 2, 0, 'alpha', 2), (3, 0, 0, 'alpha', 0), 8192...
evalf_table = {<class 'sympy.core.numbers.Zero'>: <function _create_ev...
fhalf = (0, mpz(1), -1, 1)
fnan = (0, mpz(0), -123, -1)
fnone = (1, mpz(1), 0, 1)
fone = (0, mpz(1), 0, 1)
fzero = (0, mpz(0), 0, 0)
mp = <mpmath.ctx_mp.MPContext object>
mpmath_inf = mpf('+inf')
print_function = _Feature((2, 6, 0, 'alpha', 2), (3, 0, 0, 'alpha', 0)...
rnd = 'n'
round_nearest = 'n'
FILE
/ext/anaconda3/lib/python3.5/site-packages/sympy/core/evalf.py
Help on function expand in module sympy.core.function:
expand(e, deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)
Expand an expression using methods given as hints.
Hints evaluated unless explicitly set to False are: ``basic``, ``log``,
``multinomial``, ``mul``, ``power_base``, and ``power_exp`` The following
hints are supported but not applied unless set to True: ``complex``,
``func``, and ``trig``. In addition, the following meta-hints are
supported by some or all of the other hints: ``frac``, ``numer``,
``denom``, ``modulus``, and ``force``. ``deep`` is supported by all
hints. Additionally, subclasses of Expr may define their own hints or
meta-hints.
The ``basic`` hint is used for any special rewriting of an object that
should be done automatically (along with the other hints like ``mul``)
when expand is called. This is a catch-all hint to handle any sort of
expansion that may not be described by the existing hint names. To use
this hint an object should override the ``_eval_expand_basic`` method.
Objects may also define their own expand methods, which are not run by
default. See the API section below.
If ``deep`` is set to ``True`` (the default), things like arguments of
functions are recursively expanded. Use ``deep=False`` to only expand on
the top level.
If the ``force`` hint is used, assumptions about variables will be ignored
in making the expansion.
Hints
=====
These hints are run by default
mul
---
Distributes multiplication over addition:
>>> from sympy import cos, exp, sin
>>> from sympy.abc import x, y, z
>>> (y*(x + z)).expand(mul=True)
x*y + y*z
multinomial
-----------
Expand (x + y + ...)**n where n is a positive integer.
>>> ((x + y + z)**2).expand(multinomial=True)
x**2 + 2*x*y + 2*x*z + y**2 + 2*y*z + z**2
power_exp
---------
Expand addition in exponents into multiplied bases.
>>> exp(x + y).expand(power_exp=True)
exp(x)*exp(y)
>>> (2**(x + y)).expand(power_exp=True)
2**x*2**y
power_base
----------
Split powers of multiplied bases.
This only happens by default if assumptions allow, or if the
``force`` meta-hint is used:
>>> ((x*y)**z).expand(power_base=True)
(x*y)**z
>>> ((x*y)**z).expand(power_base=True, force=True)
x**z*y**z
>>> ((2*y)**z).expand(power_base=True)
2**z*y**z
Note that in some cases where this expansion always holds, SymPy performs
it automatically:
>>> (x*y)**2
x**2*y**2
log
---
Pull out power of an argument as a coefficient and split logs products
into sums of logs.
Note that these only work if the arguments of the log function have the
proper assumptions--the arguments must be positive and the exponents must
be real--or else the ``force`` hint must be True:
>>> from sympy import log, symbols
>>> log(x**2*y).expand(log=True)
log(x**2*y)
>>> log(x**2*y).expand(log=True, force=True)
2*log(x) + log(y)
>>> x, y = symbols('x,y', positive=True)
>>> log(x**2*y).expand(log=True)
2*log(x) + log(y)
basic
-----
This hint is intended primarily as a way for custom subclasses to enable
expansion by default.
These hints are not run by default:
complex
-------
Split an expression into real and imaginary parts.
>>> x, y = symbols('x,y')
>>> (x + y).expand(complex=True)
re(x) + re(y) + I*im(x) + I*im(y)
>>> cos(x).expand(complex=True)
-I*sin(re(x))*sinh(im(x)) + cos(re(x))*cosh(im(x))
Note that this is just a wrapper around ``as_real_imag()``. Most objects
that wish to redefine ``_eval_expand_complex()`` should consider
redefining ``as_real_imag()`` instead.
func
----
Expand other functions.
>>> from sympy import gamma
>>> gamma(x + 1).expand(func=True)
x*gamma(x)
trig
----
Do trigonometric expansions.
>>> cos(x + y).expand(trig=True)
-sin(x)*sin(y) + cos(x)*cos(y)
>>> sin(2*x).expand(trig=True)
2*sin(x)*cos(x)
Note that the forms of ``sin(n*x)`` and ``cos(n*x)`` in terms of ``sin(x)``
and ``cos(x)`` are not unique, due to the identity `\sin^2(x) + \cos^2(x)
= 1`. The current implementation uses the form obtained from Chebyshev
polynomials, but this may change. See `this MathWorld article
<http://mathworld.wolfram.com/Multiple-AngleFormulas.html>`_ for more
information.
Notes
=====
- You can shut off unwanted methods::
>>> (exp(x + y)*(x + y)).expand()
x*exp(x)*exp(y) + y*exp(x)*exp(y)
>>> (exp(x + y)*(x + y)).expand(power_exp=False)
x*exp(x + y) + y*exp(x + y)
>>> (exp(x + y)*(x + y)).expand(mul=False)
(x + y)*exp(x)*exp(y)
- Use deep=False to only expand on the top level::
>>> exp(x + exp(x + y)).expand()
exp(x)*exp(exp(x)*exp(y))
>>> exp(x + exp(x + y)).expand(deep=False)
exp(x)*exp(exp(x + y))
- Hints are applied in an arbitrary, but consistent order (in the current
implementation, they are applied in alphabetical order, except
multinomial comes before mul, but this may change). Because of this,
some hints may prevent expansion by other hints if they are applied
first. For example, ``mul`` may distribute multiplications and prevent
``log`` and ``power_base`` from expanding them. Also, if ``mul`` is
applied before ``multinomial`, the expression might not be fully
distributed. The solution is to use the various ``expand_hint`` helper
functions or to use ``hint=False`` to this function to finely control
which hints are applied. Here are some examples::
>>> from sympy import expand, expand_mul, expand_power_base
>>> x, y, z = symbols('x,y,z', positive=True)
>>> expand(log(x*(y + z)))
log(x) + log(y + z)
Here, we see that ``log`` was applied before ``mul``. To get the mul
expanded form, either of the following will work::
>>> expand_mul(log(x*(y + z)))
log(x*y + x*z)
>>> expand(log(x*(y + z)), log=False)
log(x*y + x*z)
A similar thing can happen with the ``power_base`` hint::
>>> expand((x*(y + z))**x)
(x*y + x*z)**x
To get the ``power_base`` expanded form, either of the following will
work::
>>> expand((x*(y + z))**x, mul=False)
x**x*(y + z)**x
>>> expand_power_base((x*(y + z))**x)
x**x*(y + z)**x
>>> expand((x + y)*y/x)
y + y**2/x
The parts of a rational expression can be targeted::
>>> expand((x + y)*y/x/(x + 1), frac=True)
(x*y + y**2)/(x**2 + x)
>>> expand((x + y)*y/x/(x + 1), numer=True)
(x*y + y**2)/(x*(x + 1))
>>> expand((x + y)*y/x/(x + 1), denom=True)
y*(x + y)/(x**2 + x)
- The ``modulus`` meta-hint can be used to reduce the coefficients of an
expression post-expansion::
>>> expand((3*x + 1)**2)
9*x**2 + 6*x + 1
>>> expand((3*x + 1)**2, modulus=5)
4*x**2 + x + 1
- Either ``expand()`` the function or ``.expand()`` the method can be
used. Both are equivalent::
>>> expand((x + 1)**2)
x**2 + 2*x + 1
>>> ((x + 1)**2).expand()
x**2 + 2*x + 1
API
===
Objects can define their own expand hints by defining
``_eval_expand_hint()``. The function should take the form::
def _eval_expand_hint(self, **hints):
# Only apply the method to the top-level expression
...
See also the example below. Objects should define ``_eval_expand_hint()``
methods only if ``hint`` applies to that specific object. The generic
``_eval_expand_hint()`` method defined in Expr will handle the no-op case.
Each hint should be responsible for expanding that hint only.
Furthermore, the expansion should be applied to the top-level expression
only. ``expand()`` takes care of the recursion that happens when
``deep=True``.
You should only call ``_eval_expand_hint()`` methods directly if you are
100% sure that the object has the method, as otherwise you are liable to
get unexpected ``AttributeError``s. Note, again, that you do not need to
recursively apply the hint to args of your object: this is handled
automatically by ``expand()``. ``_eval_expand_hint()`` should
generally not be used at all outside of an ``_eval_expand_hint()`` method.
If you want to apply a specific expansion from within another method, use
the public ``expand()`` function, method, or ``expand_hint()`` functions.
In order for expand to work, objects must be rebuildable by their args,
i.e., ``obj.func(*obj.args) == obj`` must hold.
Expand methods are passed ``**hints`` so that expand hints may use
'metahints'--hints that control how different expand methods are applied.
For example, the ``force=True`` hint described above that causes
``expand(log=True)`` to ignore assumptions is such a metahint. The
``deep`` meta-hint is handled exclusively by ``expand()`` and is not
passed to ``_eval_expand_hint()`` methods.
Note that expansion hints should generally be methods that perform some
kind of 'expansion'. For hints that simply rewrite an expression, use the
.rewrite() API.
Examples
========
>>> from sympy import Expr, sympify
>>> class MyClass(Expr):
... def __new__(cls, *args):
... args = sympify(args)
... return Expr.__new__(cls, *args)
...
... def _eval_expand_double(self, **hints):
... '''
... Doubles the args of MyClass.
...
... If there more than four args, doubling is not performed,
... unless force=True is also used (False by default).
... '''
... force = hints.pop('force', False)
... if not force and len(self.args) > 4:
... return self
... return self.func(*(self.args + self.args))
...
>>> a = MyClass(1, 2, MyClass(3, 4))
>>> a
MyClass(1, 2, MyClass(3, 4))
>>> a.expand(double=True)
MyClass(1, 2, MyClass(3, 4, 3, 4), 1, 2, MyClass(3, 4, 3, 4))
>>> a.expand(double=True, deep=False)
MyClass(1, 2, MyClass(3, 4), 1, 2, MyClass(3, 4))
>>> b = MyClass(1, 2, 3, 4, 5)
>>> b.expand(double=True)
MyClass(1, 2, 3, 4, 5)
>>> b.expand(double=True, force=True)
MyClass(1, 2, 3, 4, 5, 1, 2, 3, 4, 5)
See Also
========
expand_log, expand_mul, expand_multinomial, expand_complex, expand_trig,
expand_power_base, expand_power_exp, expand_func, hyperexpand
תרגיל 6
הפעילו את הפונקציה simplify על הניגזרת השלישית של פונקציית הפעמון
In [21]:
Out[21]:
תרגיל 7
פשטו את הביטוי : (הפונקציה simplify)
In [22]:
Out[22]:
תרגיל 8
הפעילו על הביטוי הקודם את הפונקציה expand.
In [23]:
Out[23]:
תרגיל 9
הביטוי שלמטה הוא נוסחת הרון לחישוב שטח משולש שצלעותיו הן a,b ו-s. c הוא חצי היקף המשולש. השתמשו בפונקציה subs וחשבו את שטח המשולש אם נתון ש: a=6, b=7, c=9
קודם הציבו במקום s את מחצית סכום הצלעות ולאחר מכן הציבו את הערכים.
In [24]:
Out[24]:
בדיקת שוויון
In [25]:
Out[25]:
False
In [26]:
Out[26]:
יצירת משוואה
יוצרים משוואה באמצעות הפונקציה Eq
In [27]:
Out[27]:
In [28]:
Out[28]:
In [29]:
Out[29]:
In [30]:
Out[30]:
תרגיל 10
כתבו פונקציה המקבלת שני ביטווים. הפונקציה צריכה tupl המכיל שני ערכים בוליאניים. הראשון מציין האם הביטויים זהים והשני האם הביטויים שווים מתמטית.
In [31]:
Out[31]:
(False, False)
(False, True)
(True, True)
In [32]:
Out[32]:
(False, True)
דוגמא
קיבול חום סגול של חומר מוגדר ככמות האנרגיה שצריך לספק לכמות חומר שגודלה יחידת מסה אחת כדי לחמם אותה ב- . קיבול החום הסגולי של מים הוא
(האות J מציינת את יחידת האנרגיה ג'ול) הספק של גוף חימום שווה לכמות האנרגיה שפולט גוף החימום ביחידת זמן. יחידת ההספק היא ווט (W) והיא שווה לכמות אנרגיה של 1J בשנייה (s). בהמשך דוגמא לחישוב הזמן הדרוש לחימום דוד מים המכיל 150 ליטר מים בטמפרטורה של לטמפרטורה של בעזרת גוף חימום שהספקו 2000W.
הערה:
כאשר מצמידים גוף בטמפרטורה גבוהה לגוף בטמפרטורה נמוכה יותר עוברת אנרגיה מהגוף החם לקר עד שהטמפרטורות משתוות. כמות האנרגיה העוברת מהגוף החם לקר מכונה חום.
Q - כמות חום
T1- טמפרטורה התחלתית
T2- טמפרטורה סופית
m - מסת המים
c -קיבול חום סגולי של מים
P - הספק גוף החימום
## חישוב כמות החום הדרושה לחימום המים:
In [33]:
חישוב הזמן:
In [34]:
Out[34]:
11655.0 s
כפי שניתן לראות במקרה זה אין צורך להשתמש ב-Sympy לפתרון התרגיל.
השימוש ב- Sympy הוא הדרך הפשוטה לפתרון בעיות מסובכות והדרך המסובכת לפתרון בעיות פשוטות
תרגיל 11
נתון גוף שמסתו m1 בטמפרטורה T1 וקיבול חום C1.
מצמידים אותו לגוף שמסתו m2, הטמפרטורה שלו T2 וקיבול החום שלו C2. פתחו בעזרת Sympy
ביטוי לטמפרטורה הסופית של שני הגופים ( הניחו כי כמות החום שפלט האחד שווה לכמות החום שקלט השני).
מצמידים אותו לגוף שמסתו m2, הטמפרטורה שלו T2 וקיבול החום שלו C2. פתחו בעזרת Sympy
ביטוי לטמפרטורה הסופית של שני הגופים ( הניחו כי כמות החום שפלט האחד שווה לכמות החום שקלט השני).
In [35]:
Out[35]:
הפונקציה solve
נתונה המשוואה:
נמצא לה פתרון סימבולי:
In [36]:
Out[36]:
Eq(b*x + x - 1/x, 7)
פיתרון נומרי עבור b=5
In [37]:
Out[37]:
יותר מנעלם אחד:
נפתור את מערכת המשואות:
In [38]:
Out[38]:
תרגיל 12
חלקיק נע במהירות קצובה לאורך הקו הישר: . בנקודה (a,b) דיסקה ברדיוס r.
פתחו נוסחא באמצעותה ניתן לדעת האם החלקיק מתנגש בדיסקה ואם כן היכן.
היכן נקודת ההתנגשות עבור הערכים הבאים: a=2,b=3,m=1,n=0.5, ו- r=5
In [48]:
Out[48]:
-1.27668399491647 -0.776683994916471
מציאת נקודות קיצון של פונקציה
בנקודת קיצון הניגזרת מתאפסת
In [47]:
Out[47]:
תרגיל 12
מזריקים כמות A של תרופה לחולה. הריכוז c של התרופה נימדד ב: .
כעבור זמן t מרגע הזרקת התרופה הריכוז ניתן על ידי : . הזמן נימדד בדקות.
הריכוז המקסימאלי המותר של התרופה הוא
כעבור זמן t מרגע הזרקת התרופה הריכוז ניתן על ידי : . הזמן נימדד בדקות.
הריכוז המקסימאלי המותר של התרופה הוא
- איזו כמות מקסימאלית A מותר להזריק ? ומתי מתקבל הריכוז המקסימאלי?
- שרטטו גרף של הריכוז בדם כתלות בזמן והעריכו באמצעותו מתי מתקבל ריכוז של
- מצאו לסעיף הקודם תשובה מדויקת בעזרת הפונקציה nsolv.
-כל כמה זמן צריך להזריק לחולה את התרופה כדי שהריכוז לא יהיה מעבר לערך המקסימאלי ולא יפחת מערך מינימאלי של
In [50]:
Out[50]:
Solution 1 is: 0.305
Solution 2 is: 11.1
8.08 minutes