Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download

11th grade-all tasks

2151 views
Kernel: Python 3 (old Anaconda 3)
Name = ["Roey Dvir"] Name
['Roey Dvir']

החבילה SymPy


SymPy היא ספרייה למתמטיקה סימבולית המיועדת ל- Python. היא כתובה כולה רק ב-Python, כך שאין צורך בסיפריות נוספות כדי להשתמש בה. בכוונת מפתחי ה- Sympy לפתחה עד כדי מערכת המכילה את כל התכונות והיכולות של תוכנות CAS, ראשי תיבות של Computer Algebric System. המפתחים מנסים לשמור את הקוד פשוט ככל האפשר כדי ליצור חבילה קלה להבנה ושאפשר להרחיבה בקלות. באופן בסיסי Sympy היא מחשבון סימבולי, אבל יתרונה בכך שאפשר להשתמש בה בתוכנית מחשב.
import sympy as sp sp.init_printing()

תרגיל 1

חשבו: acos(1)acos(-1)
5\sqrt5 9\sqrt9
import sympy as sp #from sympy import * sp.init_printing() display(sp.acos(-1), sp.sqrt(5).evalf(), sp.sqrt(9))
π\pi
2.236067977499792.23606797749979
33

Symbols

האוביקט הבסיסי ב- Sympy הוא ה- Symbol אוביקט זה מייצג משתנה מתמטי. יצירת אובייקט זה נעשיית באמצעות הפונקציה Symbol
alpha=sp.Symbol('alpha') sp.sin(alpha)**2
sin2(α)\sin^{2}{\left (\alpha \right )}

תרגיל 2

בעזרת הפונקציה symbols צרו את המשתנים μ\mu ו- σ\sigma (החליפו את ה- ? בקוד המתאים)
import sympy as sp sp.init_printing() mu,sigma=sp.symbols('mu sigma') display(mu,sigma)
μ\mu
σ\sigma

תרגיל 3

הגדירו את הפונקציה e(xμ)2σ2e^{ {-(x-\mu)^2}\over{\sigma^2}} פונקציה זו מכונה פונקציית הפעמון.
את הפונקציה exe^x מגדירים כ- (exp(x
import sympy as sp x,mu,sigma=sp.symbols('x mu sigma') bell = sp.exp((-(x-mu)**2)/(sigma**2)) bell
e1σ2(μ+x)2e^{- \frac{1}{\sigma^{2}} \left(- \mu + x\right)^{2}}

גזירה של פונקציה

a=sp.Symbol('a') sp.diff(a*x**3,x)
3ax23 a x^{2}
bell.diff(x)
1σ2(2μ+2x)e1σ2(μ+x)2- \frac{1}{\sigma^{2}} \left(- 2 \mu + 2 x\right) e^{- \frac{1}{\sigma^{2}} \left(- \mu + x\right)^{2}}

שרטוט גרף באמצעות sympy.plotting

%matplotlib -- inline from sympy.plotting import * sp.plot(sp.exp(-(x-3)**2),(x,-1,6))
Image in a Jupyter notebook
<sympy.plotting.plot.Plot at 0x7fd93dbeec50>

תרגיל 4

חשבו את הניגזרת השנייה של פונקציית "הפעמון" ושרטטו גרף שלה (הניחו כי :σ=3.0\sigma=3.0 ו- μ=1.5\mu=1.5 )
הערה: חשבו את הנגזרת ולאחר מכן הגדירו את ביטוי הניגזרת מחדש כאשר אתם מציבים ערכים לפרמטרים: μ,σ\mu,\sigma.
import sympy as sp x,mu,sigma=sp.symbols('x mu sigma') bell=sp.exp((-(x-mu)**2)/(sigma**2)) belldd=bell.diff(x).diff(x) bellddvalue=belldd.subs([(mu,1.5),(sigma,3)]) bellddvalue sp.plot(bellddvalue,(x,-1,6))
Image in a Jupyter notebook
<sympy.plotting.plot.Plot at 0x7fd93bae5f98>

הפונקציות simplify, subs,expand,evalf

a,b,c,d=sp.symbols('a b c d') expr=(a-b)*(a+b)**2 sp.expand(expr)
a3+a2bab2b3a^{3} + a^{2} b - a b^{2} - b^{3}
expr.expand()
a3+a2bab2b3a^{3} + a^{2} b - a b^{2} - b^{3}
new_expr=expr.subs([(a,3),(b,d*c/2)]) new_expr
(cd2+3)(cd2+3)2\left(- \frac{c d}{2} + 3\right) \left(\frac{c d}{2} + 3\right)^{2}
display(sp.simplify(new_expr), sp.simplify(new_expr).evalf())
18(cd+6)(cd+6)2\frac{1}{8} \left(- c d + 6\right) \left(c d + 6\right)^{2}
0.125(cd+6.0)(cd+6.0)20.125 \left(- c d + 6.0\right) \left(c d + 6.0\right)^{2}
new_expr.subs([(c,2.4),(d,3)])
26.136-26.136

תרגיל 5

בעזרת הפונקציה help בדקו מה פעולת הפונקציה simplify.

מה עושה כל אחת מהפונקציות subs, evalf ו- expand

help(sp.simplify) #Simplifies an expression help(sp.evalf) #Changes a number's type to float help(sp.expand) #Expands an expression #help(new_expr.subs([(x,1)])) #Replaces a symbol by a number
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 על הניגזרת השלישית של פונקציית הפעמון
bellddd=bell.diff(x).diff(x).diff(x) bellddd.simplify()
1σ6(12σ2(μ+x)+8(μx)3)e1σ2(μx)2\frac{1}{\sigma^{6}} \left(12 \sigma^{2} \left(- \mu + x\right) + 8 \left(\mu - x\right)^{3}\right) e^{- \frac{1}{\sigma^{2}} \left(\mu - x\right)^{2}}

תרגיל 7

פשטו את הביטוי : (x+1)21x2 (x+1)^2 \over {1-x^2} (הפונקציה simplify)
func = ((x+1)**2)/(1-x**2) func.simplify()
x+1x1- \frac{x + 1}{x - 1}

תרגיל 8

הפעילו על הביטוי הקודם את הפונקציה expand.
func.expand()
x2x2+1+2xx2+1+1x2+1\frac{x^{2}}{- x^{2} + 1} + \frac{2 x}{- x^{2} + 1} + \frac{1}{- x^{2} + 1}

תרגיל 9

הביטוי שלמטה הוא נוסחת הרון לחישוב שטח משולש שצלעותיו הן a,b ו-s. c הוא חצי היקף המשולש. השתמשו בפונקציה subs וחשבו את שטח המשולש אם נתון ש: a=6, b=7, c=9
קודם הציבו במקום s את מחצית סכום הצלעות ולאחר מכן הציבו את הערכים.
a,b,c=sp.symbols('a,b,c') s=(a+b+c)/2 area=sp.sqrt(s*(s-a)*(s-b)*(s-c)).simplify() areavalue=area.subs([(a,6),(b,7),(c,9)]) display(area, areavalue.evalf())
14(a+b+c)(ab+c)(a+bc)(a+b+c)\frac{1}{4} \sqrt{\left(- a + b + c\right) \left(a - b + c\right) \left(a + b - c\right) \left(a + b + c\right)}
20.97617696340320.976176963403

בדיקת שוויון

#Not the way x,y=sp.symbols('x y') a=(x-y)**2 b=x**2-2*x*y+y**2 a==b
False
#The way sp.simplify(a-b)
00

יצירת משוואה

יוצרים משוואה באמצעות הפונקציה Eq
eq=sp.Eq(y,4*x**2-x+3) eq
y=4x2x+3y = 4 x^{2} - x + 3
eq.lhs
yy
eq.rhs
4x2x+34 x^{2} - x + 3
sp.solve(eq,x)
[1816y47+18,1816y47+18]\left [ - \frac{1}{8} \sqrt{16 y - 47} + \frac{1}{8}, \quad \frac{1}{8} \sqrt{16 y - 47} + \frac{1}{8}\right ]

תרגיל 10

כתבו פונקציה המקבלת שני ביטווים. הפונקציה צריכה tupl המכיל שני ערכים בוליאניים. הראשון מציין האם הביטויים זהים והשני האם הביטויים שווים מתמטית.
def equality_exercise(a,b): if(a==b): b1=True else: b1=False if(sp.simplify(a-b)==0): b2=True else: b2=False return(b1,b2) display(equality_exercise(x,2), equality_exercise((x+1)**2,x**2+2*x+1), equality_exercise(4*x,4*x)) #Return a tuple of tow boolean. the first is True if a=b symbolicaly, #the second is True if a==b mathematically. #Examples #======== #>>> x=symbols('x') #>>> equality_exercise(x,2) #(False,False) #>>> equality_exercise((x+1)**2,x**2+2*x+1) #(False,True) #>>> equality_exercise(4*x,4*x) #(True,True)
(False, False)
(False, True)
(True, True)
expr1=(x-y)**2 expr2=x**2-2*x*y+y**2 equality_exercise(expr1,expr2)
(False, True)

דוגמא

קיבול חום סגול של חומר מוגדר ככמות האנרגיה שצריך לספק לכמות חומר שגודלה יחידת מסה אחת כדי לחמם אותה ב- 10C 1^0C . קיבול החום הסגולי של מים הוא 4.2Jgr10C 4.2{ J\over {gr\cdot 1^0C}} (האות J מציינת את יחידת האנרגיה ג'ול) הספק של גוף חימום שווה לכמות האנרגיה שפולט גוף החימום ביחידת זמן. יחידת ההספק היא ווט (W) והיא שווה לכמות אנרגיה של 1J בשנייה (s). בהמשך דוגמא לחישוב הזמן הדרוש לחימום דוד מים המכיל 150 ליטר מים בטמפרטורה של 230C 23^0 C לטמפרטורה של 600C 60^0C בעזרת גוף חימום שהספקו 2000W.
הערה:
כאשר מצמידים גוף בטמפרטורה גבוהה לגוף בטמפרטורה נמוכה יותר עוברת אנרגיה מהגוף החם לקר עד שהטמפרטורות משתוות. כמות האנרגיה העוברת מהגוף החם לקר מכונה חום.

Q - כמות חום

T1- טמפרטורה התחלתית

T2- טמפרטורה סופית

m - מסת המים

c -קיבול חום סגולי של מים

P - הספק גוף החימום

##

חישוב כמות החום הדרושה לחימום המים:

c=4.2# J/(gr*C) m=150*1000 #gr T1=23 #C T2=60 #C #T3=? P=2000 #W=J/s Q=c*m*(T2-T1) #T2=T3

חישוב הזמן:

t=Q/P print(t, "s")
11655.0 s
כפי שניתן לראות במקרה זה אין צורך להשתמש ב-Sympy לפתרון התרגיל.

השימוש ב- Sympy הוא הדרך הפשוטה לפתרון בעיות מסובכות והדרך המסובכת לפתרון בעיות פשוטות

תרגיל 11

נתון גוף שמסתו m1 בטמפרטורה T1 וקיבול חום C1.
מצמידים אותו לגוף שמסתו m2, הטמפרטורה שלו T2 וקיבול החום שלו C2. פתחו בעזרת Sympy
ביטוי לטמפרטורה הסופית של שני הגופים ( הניחו כי כמות החום שפלט האחד שווה לכמות החום שקלט השני).
import sympy as sp m1,T1,C1,m2,T2,C2,T=sp.symbols("m1 T1 C1 m2 T2 C2 T") #T=? Q1=C1*m1*(T-T1) Q2=C2*m2*(T-T2) eq=sp.Eq(Q1,-Q2) sp.solve(eq,[T,T1,C1,m2,T2,C2,m1])[0][T]
C1T1m1+C2T2m2C1m1+C2m2\frac{C_{1} T_{1} m_{1} + C_{2} T_{2} m_{2}}{C_{1} m_{1} + C_{2} m_{2}}

הפונקציה solve

נתונה המשוואה: x1x+bx=7 x- {1\over x}+b\cdot x=7
נמצא לה פתרון סימבולי:
x,b=sp.symbols('x b') eq=sp.Eq(x-1/x+b*x,7) print(eq) ans=sp.solve(eq,x) ans
Eq(b*x + x - 1/x, 7)
[4b+53+72(b+1),4b+53+72(b+1)]\left [ \frac{- \sqrt{4 b + 53} + 7}{2 \left(b + 1\right)}, \quad \frac{\sqrt{4 b + 53} + 7}{2 \left(b + 1\right)}\right ]

פיתרון נומרי עבור b=5

x,b=sp.symbols('x b') eq=sp.Eq(x-1/x+b*x,7) ans=sp.solve(eq,x) display(ans[0].subs(b,5).n(6), ans[1].subs(b,5).n(6))
0.128667-0.128667
1.295331.29533

יותר מנעלם אחד:

נפתור את מערכת המשואות:
3(xy)2+x2=yyx+x3+y=1\begin{darray}{rcl} 3(x-y)^2+x-2=y\\ y\cdot x+\frac{x}{3}+y=1 \end{darray}
x,y=sp.symbols('x,y') sp.solve([sp.Eq(3*(x-y)**2+x-2,y),sp.Eq(y*x+x/3+y,1)],[x,y])
[(73,43),(53,73),(0,1),(1,13)]\left [ \left ( - \frac{7}{3}, \quad - \frac{4}{3}\right ), \quad \left ( - \frac{5}{3}, \quad - \frac{7}{3}\right ), \quad \left ( 0, \quad 1\right ), \quad \left ( 1, \quad \frac{1}{3}\right )\right ]

תרגיל 12

חלקיק נע במהירות קצובה לאורך הקו הישר: y=mx+n y=m\cdot x+n . בנקודה (a,b) דיסקה ברדיוס r.
פתחו נוסחא באמצעותה ניתן לדעת האם החלקיק מתנגש בדיסקה ואם כן היכן.
היכן נקודת ההתנגשות עבור הערכים הבאים: a=2,b=3,m=1,n=0.5, ו- r=5
x,m,n,r=sp.symbols("x m n r") y=m*x+n f=sp.sqrt((x-a)**2+(y-b)**2) eq=sp.Eq(f,r) display(sp.solve(eq,x)[0]) eqvalues=eq.subs([(m,1),(n,0.5),(r,5),(a,2),(b,3)]) x1=sp.solve(eqvalues,x)[0] y1=y.subs([(m,1),(n,0.5),(x,x1)]) print(x1,y1)
1m2+1(a+bmmna2m2+2abm2amnb2+2bn+m2r2n2+r2)\frac{1}{m^{2} + 1} \left(a + b m - m n - \sqrt{- a^{2} m^{2} + 2 a b m - 2 a m n - b^{2} + 2 b n + m^{2} r^{2} - n^{2} + r^{2}}\right)
-1.27668399491647 -0.776683994916471

מציאת נקודות קיצון של פונקציה

בנקודת קיצון הניגזרת מתאפסת

f(x)=e(x2ax+b)c f(x)=e^\frac{-(x^2-ax+b)}{c}

import sympy as sp from sympy.plotting import plot x,a,b,c=sp.symbols('x,a,b,c') f=sp.exp(-(x**2-a*x+b)/c) xzero=sp.solve(sp.Eq(f.diff(x),0),x) y=[f.subs([(x,xzero[0])]),f.subs([(x,xzero[1])]),f.subs([(x,xzero[2])])] (xzero[1],y[1]),(xzero[1],y[1]),(xzero[2],y[2])
((a212a24b+~,e1c(a(a212a24b+~)b(a212a24b+~)2)),(a212a24b+~,e1c(a(a212a24b+~)b(a212a24b+~)2)),(a2+12a24b+~,e1c(a(a2+12a24b+~)b(a2+12a24b+~)2)))\left ( \left ( \frac{a}{2} - \frac{1}{2} \sqrt{a^{2} - 4 b + \tilde{\infty}}, \quad e^{\frac{1}{c} \left(a \left(\frac{a}{2} - \frac{1}{2} \sqrt{a^{2} - 4 b + \tilde{\infty}}\right) - b - \left(\frac{a}{2} - \frac{1}{2} \sqrt{a^{2} - 4 b + \tilde{\infty}}\right)^{2}\right)}\right ), \quad \left ( \frac{a}{2} - \frac{1}{2} \sqrt{a^{2} - 4 b + \tilde{\infty}}, \quad e^{\frac{1}{c} \left(a \left(\frac{a}{2} - \frac{1}{2} \sqrt{a^{2} - 4 b + \tilde{\infty}}\right) - b - \left(\frac{a}{2} - \frac{1}{2} \sqrt{a^{2} - 4 b + \tilde{\infty}}\right)^{2}\right)}\right ), \quad \left ( \frac{a}{2} + \frac{1}{2} \sqrt{a^{2} - 4 b + \tilde{\infty}}, \quad e^{\frac{1}{c} \left(a \left(\frac{a}{2} + \frac{1}{2} \sqrt{a^{2} - 4 b + \tilde{\infty}}\right) - b - \left(\frac{a}{2} + \frac{1}{2} \sqrt{a^{2} - 4 b + \tilde{\infty}}\right)^{2}\right)}\right )\right )

תרגיל 12

מזריקים כמות A של תרופה לחולה. הריכוז c של התרופה נימדד ב: mgml \frac{mg}{ml} .
כעבור זמן t מרגע הזרקת התרופה הריכוז ניתן על ידי : c(t)=Atet/3 c(t)=Ate^{-t/3} . הזמן נימדד בדקות.
הריכוז המקסימאלי המותר של התרופה הוא 1mgml 1 \frac{mg}{ml}
- איזו כמות מקסימאלית A מותר להזריק ? ומתי מתקבל הריכוז המקסימאלי?
- שרטטו גרף של הריכוז בדם כתלות בזמן והעריכו באמצעותו מתי מתקבל ריכוז של 0.25mgml 0.25 \frac{mg}{ml}
- מצאו לסעיף הקודם תשובה מדויקת בעזרת הפונקציה nsolv.
-כל כמה זמן צריך להזריק לחולה את התרופה כדי שהריכוז לא יהיה מעבר לערך המקסימאלי ולא יפחת מערך מינימאלי של 0.25mgml 0.25 \frac{mg}{ml}
## When t*exp(-t/3) is max import sympy as sp A,t=sp.symbols("A t") c=A*t*sp.exp(-t/3) cdot=c.diff(t) eq1=sp.Eq(cdot,0) tmax=sp.solve(eq1,t)[0] cmax=1 eq2=sp.Eq(cmax,c.subs([(t,tmax)])) Amax=sp.solve(eq2,A)[0] display(Amax,tmax) c2=c.subs([(A,Amax)]) display(c2) sp.plot(c2, (t, 0, 100), title="c(t)") #Approximately in 0.3 seconds c3=sp.Eq(c2, 0.25) sol1=sp.nsolve(c3, t, 0) sol2=sp.nsolve(c3, t, 11) print("Solution 1 is: ", sol1.n(3)) print("Solution 2 is: ", sol2.n(3)) x = sol2 - tmax print(x.n(3), "minutes")
e3\frac{e}{3}
33
et3et3\frac{e t}{3} e^{- \frac{t}{3}}
Image in a Jupyter notebook
Solution 1 is: 0.305 Solution 2 is: 11.1 8.08 minutes