L iH<ddlmZmZmZmZmZddlmZddZddZ y))arangenewaxishstackprodarray)linalgcH||dzkr td|dzdk(r td|dz }t| |dz}|ddtf}|dz}td|D]}t |||zg}t td|dzd t j||z}|S) a Return weights for an Np-point central derivative. Assumes equally-spaced function points. If weights are in the vector w, then derivative is w[0] * f(x-ho*dx) + ... + w[-1] * f(x+h0*dx) Parameters ---------- Np : int Number of points for the central derivative. ndiv : int, optional Number of divisions. Default is 1. Returns ------- w : ndarray Weights for an Np-point central derivative. Its size is `Np`. Notes ----- Can be inaccurate for a large number of points. Examples -------- We can calculate a derivative value of a function. >>> def f(x): ... return 2 * x**2 + 3 >>> x = 3.0 # derivative point >>> h = 0.1 # differential step >>> Np = 3 # point number for central derivative >>> weights = _central_diff_weights(Np) # weights for first derivative >>> vals = [f(x + (i - Np/2) * h) for i in range(Np)] >>> sum(w * v for (w, v) in zip(weights, vals))/h 11.79999999999998 This value is close to the analytical solution: f'(x) = 4x, so f'(3) = 12 References ---------- .. [1] https://en.wikipedia.org/wiki/Finite_difference z;Number of points must be at least the derivative order + 1.rz!The number of points must be odd.?Naxis) ValueErrorrrrangerrrinv)NpndivhoxXkws e/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/scipy/stats/_finite_differences.py_central_diff_weightsrs^ D1H} I   Av{<== qBsBHA !W* A 3A 1b\ Aq!t9  VAtax q)FJJqM$,??A Hc||dzkr td|dzdk(r td|dk(re|dk(rtgddz }n|d k(rtgd d z }n|d k(rtgd dz }n|dk(rtgddz }nt|d}ns|dk(rb|dk(rtgd}n[|d k(rtgdd z }nE|d k(rtgddz }n/|dk(rtgddz }nt|d}n t||}d}|dz }t|D]} ||| ||| |z |zzg|zz }|t |f|zdz S)a  Find the nth derivative of a function at a point. Given a function, use a central difference formula with spacing `dx` to compute the nth derivative at `x0`. Parameters ---------- func : function Input function. x0 : float The point at which the nth derivative is found. dx : float, optional Spacing. n : int, optional Order of the derivative. Default is 1. args : tuple, optional Arguments order : int, optional Number of points to use, must be odd. Notes ----- Decreasing the step size too small can result in round-off error. Examples -------- >>> def f(x): ... return x**3 + x**2 >>> _derivative(f, 1.0, dx=1e-6) 4.9999999999217337 r zm'order' (the number of points used to compute the derivative), must be at least the derivative order 'n' + 1.r rzJ'order' (the number of points used to compute the derivative) must be odd.)rr g@)r irrg(@)r ir-r gN@r#) rii`riiX g@@)r gr )rir)r)r ir+r*r gf@) r%ir.r-r,r%g@r r)rrrrr) funcx0dxnargsorderweightsvalrrs r _derivativer7EsD q1u} =   qyA~    Av A:J'#-G aZ-.5G aZ67$>G aZEFNG+E15G a A:L)G aZ12T9G aZ<=EG aZJK  ,E15G'q1 C !B 5\< wqzDq2vm!3;d;;;< reaia( ((rN)r )r r r) numpyrrrrrscipyrrr7r8rrr;s66= @L)r