
    wg              
           d dl mZ d dlmZ d dlmZmZ d dlmZm	Z	 d dl
mZ d dlmZmZ d dlmZ d dlmZmZmZmZmZmZmZmZmZmZmZmZmZ d d	lm Z  	 dddd
d
d dd
d
ddZ!d Z"d
d e       fd
ddZ#y
)    )Tuple)oo)GtLt)DummySymbol)Abs)MinMax)And)
AssignmentAddAugmentedAssignmentbreak_	CodeBlockDeclarationFunctionDefinitionPrintReturnScopeWhileVariablePointerreal)isnanNgؗҼ<Fc                 ,    |  | j                  |      z  S N)diff)exs     ]/home/mcse/projects/flask/flask-venv/lib/python3.12/site-packages/sympy/codegen/algorithms.py<lambda>r!      s    aRq	\     )rtoldebugitermaxcounterdelta_fncse
handle_nanboundsc                ~   |t               }t        }d}nd }|j                  } || |      }|	rQddlm}	  |	|j                         g      \  }\  }|D cg c]  \  }}t        ||       }}}|t        ||      gz  }nt        ||      g}|
'|t        t        |      t        |
t                    gz  }|t        ||      gz  }|*|t        |t        t        ||d         |d               gz  }|r.t        ||gdj                  |j                  |            }||gz  }t!        t#        |      ||t#        |      z  z         }t%        t'        |t(        t*                    g}|q|xs t        d	      }t'        j,                  |d      }|j/                  t%        |             |j/                  t        |d             t1        |t3        ||            }t        |t        |       }|}|r5|j/                  t        |gd
j                  |j                                     ||gz  } |t        |       S c c}}w )a   Generates an AST for Newton-Raphson method (a root-finding algorithm).

    Explanation
    ===========

    Returns an abstract syntax tree (AST) based on ``sympy.codegen.ast`` for Netwon's
    method of root-finding.

    Parameters
    ==========

    expr : expression
    wrt : Symbol
        With respect to, i.e. what is the variable.
    atol : number or expression
        Absolute tolerance (stopping criterion)
    rtol : number or expression
        Relative tolerance (stopping criterion)
    delta : Symbol
        Will be a ``Dummy`` if ``None``.
    debug : bool
        Whether to print convergence information during iterations
    itermax : number or expr
        Maximum number of iterations.
    counter : Symbol
        Will be a ``Dummy`` if ``None``.
    delta_fn: Callable[[Expr, Symbol], Expr]
        computes the step, default is newtons method. For e.g. Halley's method
        use delta_fn=lambda e, x: -2*e*e.diff(x)/(2*e.diff(x)**2 - e*e.diff(x, 2))
    cse: bool
        Perform common sub-expression elimination on delta expression
    handle_nan: Token
        How to handle occurrence of not-a-number (NaN).
    bounds: Optional[tuple[Expr, Expr]]
        Perform optimization within bounds

    Examples
    ========

    >>> from sympy import symbols, cos
    >>> from sympy.codegen.ast import Assignment
    >>> from sympy.codegen.algorithms import newtons_method
    >>> x, dx, atol = symbols('x dx atol')
    >>> expr = cos(x) - x**3
    >>> algo = newtons_method(expr, x, atol=atol, delta=dx)
    >>> algo.has(Assignment(dx, -expr/expr.diff(x)))
    True

    References
    ==========

    .. [1] https://en.wikipedia.org/wiki/Newton%27s_method

    deltac                     | S r    )r   s    r    r!   z newtons_method.<locals>.<lambda>P   s    A r"   r   )r(      z{}=%12.5g {}=%12.5g\n)typevalueT)integerz{}=%12.5g\n)r   r   namesympy.simplify.cse_mainr(   factorr   r   r   r   r   r   r
   r   r   formatr   r	   r   r   r   r   deducedappendr   r   )exprwrtatolr,   r#   r$   r%   r&   r'   r(   r)   r*   Wrappername_d
delta_exprcsesreddumsub_ewhl_bdyprntreqdeclars	v_counterwhlblcks                             r    newtons_methodrJ      s#   v }$$J
/J--/01fs<@Ajc5:c5)AAJuc*++eZ01E%,	*f(EFGG&sE233GJsCC(;VAY$GHIIc5\#;#B#B388V#TUD6
SZSX-
.C8EB?@AG0U40$$Wa0	{9-.-gq9:#r'7+,
Y(
)CDE3%!6!6sxx!@ABSEMD9d#$$3 Bs   H9c                     t        | t              r| j                  j                  } | S t        | t              r| j                  } | S r   )
isinstancer   variablesymbolr   )args    r    
_symbol_ofrP   s   s<    #{#ll!! J 
C	"jjJr"   newton)r,   c          	         ||f}|D ci c]?  }t        |t              r-|j                  t        d|j                  j                  z        A }}|+t        d|j                  z         }| j                  |      rd}t        | |fd|i|j                  |      }	t        |	t              r|	j                  }	| j                  j                  |D ch c]  }t        |       c}      }
|
r+t        ddj                  t        t         |
            z        t#        d |D              }t%        |	t'        |            }t)        t*        ||||      S c c}w c c}w )	a   Generates an AST for a function implementing the Newton-Raphson method.

    Parameters
    ==========

    expr : expression
    wrt : Symbol
        With respect to, i.e. what is the variable
    params : iterable of symbols
        Symbols appearing in expr that are taken as constants during the iterations
        (these will be accepted as parameters to the generated function).
    func_name : str
        Name of the generated function.
    attrs : Tuple
        Attribute instances passed as ``attrs`` to ``FunctionDefinition``.
    \*\*kwargs :
        Keyword arguments passed to :func:`sympy.codegen.algorithms.newtons_method`.

    Examples
    ========

    >>> from sympy import symbols, cos
    >>> from sympy.codegen.algorithms import newtons_method_function
    >>> from sympy.codegen.pyutils import render_as_module
    >>> x = symbols('x')
    >>> expr = cos(x) - x**3
    >>> func = newtons_method_function(expr, x)
    >>> py_mod = render_as_module(func)  # source code as string
    >>> namespace = {}
    >>> exec(py_mod, namespace, namespace)
    >>> res = eval('newton(0.5)', namespace)
    >>> abs(res - 0.865474033102) < 1e-12
    True

    See Also
    ========

    sympy.codegen.algorithms.newtons_method

    Nz(*%s)d_r,   zMissing symbols in params: %sz, c              3   <   K   | ]  }t        |t                y wr   )r   r   ).0ps     r    	<genexpr>z*newtons_method_function.<locals>.<genexpr>   s     6!HQ%6s   )attrs)rL   r   rN   r   r3   hasrJ   xreplacer   bodyfree_symbols
differencerP   
ValueErrorjoinmapstrtupler   r   r   r   )r9   r:   params	func_namerX   r,   kwargsrV   pointer_subsalgonot_in_paramsrF   r[   s                r    newtons_method_functionri   {   s4   R ~#?z!W'= HHfWqxx}}%<== ?L ?}tchh'88E?E$;5;F;DD\RD$yy%%001PA*Q-1PQM8499SmE\;]]^^6v66GT6#;'DdIwEJJ? 2Qs   AEE)g-q=N)$sympy.core.containersr   sympy.core.numbersr   sympy.core.relationalr   r   sympy.core.symbolr   r   $sympy.functions.elementary.complexesr	   (sympy.functions.elementary.miscellaneousr
   r   sympy.logic.boolalgr   sympy.codegen.astr   r   r   r   r   r   r   r   r   r   r   r   r   sympy.codegen.cfunctionsr   rJ   rP   ri   r.   r"   r    <module>rs      sv    ' ! * - 4 = #    + U`%e58Q`%F /3heg 9K`d 9Kr"   