示例#1
0
def specAnglesCalc(valxrel, valyrel, valrA, valrB):
    
    x = syp.Symbol('x')
    y = syp.Symbol('y')
    xrel = syp.Symbol('xrel')
    yrel = syp.Symbol('yrel')
    rA = syp.Symbol('rA')
    rB = syp.Symbol('rB')

    circleA = syp.Eq(((x-xrel)**2) + ((y-yrel)**2), (rA**2))
    circleB = syp.Eq((x**2) + (y**2), (rB**2))

    solveArray = syp.solve([circleA, circleB], (x, y))

    subsDic = {xrel:valxrel, yrel:valyrel, rA:valrA, rB:valrB}

    solutions = []
    angles = []
    for i in range(0,len(solveArray)):
        pointx = syp.N(solveArray[i][0], subs=subsDic)
        pointy = syp.N(solveArray[i][1], subs=subsDic)

        print('Point x at:')
        print(pointx)

        print('Point y at:')
        print(pointy)

        solutions.append([pointx,pointy])
        angles.append(math.atan2(pointy, pointx))

    return angles
示例#2
0
文件: oo.py 项目: nesanter/spkrtools
    def lt_spl_xlimited(self, lt, athz=20, N=True):
        """
        Solve for excursion-limited SPL at given frequency
        with given transform

        This is designed to test safe maximum SPL for when
        a Linkwitz Transform is applied

        Args:
            lt: the transform in SOS form
            athz: minimum test frequency in Hz (default 20)
            N: return reduced value (default True)

        Returns:
            maximum dbSPL
        """
        xbase = box.Xspl.subs(self.values).subs({hz: athz})
        adjust = y.N(
            filters.freqz((lt, ), hz / 24000, dB=True).subs({hz: athz}))

        r = (xbase - adjust)
        if N:
            return y.N(r)
        else:
            return r
示例#3
0
    def inverse_kinematics(self, x, y):
        """
        This function will compute the required theta_0 and theta_1 angles to position the 
        foot to the point x, y. We will use an iterative solver to determine the angles.
        """
        error = Matrix([1, 1])
        (theta_0, theta_1) = self.get_joint_pos()

        while error.norm() > 3e-2:

            (alpha_0, alpha_1) = self.compute_internal_angles(theta_0, theta_1)

            current_x = l_base / 2 + l1 * cos(theta_0) + l2 * cos(alpha_0)
            current_y = l1 * sin(theta_0) + l2 * sin(alpha_0)
            error = sympy.N(Matrix([x - current_x, y - current_y]))

            J1 = self.J.subs([(theta0_sym, theta_0), (theta1_sym, theta_1),
                              (alpha0_sym, alpha_0), (alpha1_sym, alpha_1)])
            J1 = sympy.N(J1)
            J1_inv = J1.pinv()

            increment = J1_inv @ error * 0.08
            theta_0 = theta_0 + increment[0]
            theta_1 = theta_1 + increment[1]
            if theta_0 > 0.5 * math.pi:
                if theta_0 < 1.5 * math.pi:
                    theta_0 = theta_0 - math.pi

        return (theta_0, theta_1)
示例#4
0
def a(n):
    if n == 0 or n == 1:
        return sp.N(1)
    elif n == 2:
        return sp.N(5)
    else:
        return sp.N(3*a(n-1) + 3*a(n-2) - a(n-3))
示例#5
0
def test_xk(k):
    n = 10

    moments = quadpy.tools.integrate(
        lambda x: [x**(i + k) for i in range(2 * n)], -1, +1)

    alpha, beta = quadpy.tools.chebyshev(moments)

    assert (alpha == 0).all()
    assert beta[0] == moments[0]
    assert beta[1] == sympy.S(k + 1) / (k + 3)
    assert beta[2] == sympy.S(4) / ((k + 5) * (k + 3))
    quadpy.tools.scheme_from_rc(numpy.array([sympy.N(a) for a in alpha],
                                            dtype=float),
                                numpy.array([sympy.N(b) for b in beta],
                                            dtype=float),
                                mode='numpy')

    # a, b = \
    #     orthopy.line_segment.recurrence_coefficients.legendre(
    #             2*n, mode='sympy'
    #             )

    # moments = quadpy.tools.integrate(
    #         lambda x: x**2, -1, +1, 2*n,
    #         polynomial_class=quadpy.tools.legendre
    #         )
    # alpha, beta = quadpy.tools.chebyshev_modified(moments, a, b)
    # points, weights = quadpy.tools.scheme_from_rc(
    #         numpy.array([sympy.N(a) for a in alpha], dtype=float),
    #         numpy.array([sympy.N(b) for b in beta], dtype=float)
    #         )
    return
示例#6
0
    def __init__(self, soln_diffs, exact_solns, rhs_diffs, dbl_rhss):

        self.soln_diffs = soln_diffs
        self.exact_solns = exact_solns
        self.rhs_diffs = rhs_diffs
        self.rhss = [
            sympy.Matrix(map(sympy.Rational, (rhs[0][0], rhs[1][0])))
            for rhs in dbl_rhss
        ]

        soln_rel_errs = [
            soln_diff.norm() / soln.norm()
            for soln_diff, soln in zip(self.soln_diffs, self.exact_solns)
        ]
        rhs_rel_errs = [
            rhs_diff.norm() / rhs.norm()
            for rhs_diff, rhs in zip(self.rhs_diffs, self.rhss)
        ]
        cond_lowers = [
            soln_rel_err / rhs_rel_err
            for soln_rel_err, rhs_rel_err in zip(soln_rel_errs, rhs_rel_errs)
        ]

        self.soln_rel_errs = [
            sympy.N(soln_rel_err) for soln_rel_err in soln_rel_errs
        ]
        self.rhs_rel_errs = [
            sympy.N(rhs_rel_err) for rhs_rel_err in rhs_rel_errs
        ]
        self.cond_lowers = [sympy.N(cond_lower) for cond_lower in cond_lowers]
示例#7
0
    def evaluacion_minima(self, valores, puntos):
        puntonuevo = []
        evaluacionf = []

        for j in range(0, len(valores)):
            evaluacionf.append(0)

        for l in range(0, 2):
            puntonuevo.append(0)

        for i in range(0, len(valores)):
            raiz = str(sp.N(valores[i])).split()[0]
            evaluacionf[i] = self.f.subs([(x, puntos[0].subs([(t, raiz)])),
                                          (y, puntos[1].subs([(t, raiz)]))])

        pos = evaluacionf.index(min(evaluacionf))
        self.lamb = str(sp.N(valores[pos])).split()[0]

        a1 = puntos[0].subs([(t, self.lamb)])
        a2 = puntos[1].subs([(t, self.lamb)])

        n1 = str(sp.N(a1)).split()[0]
        n2 = str(sp.N(a2)).split()[0]

        puntonuevo[0] = N(n1)
        puntonuevo[1] = N(n2)

        return puntonuevo
示例#8
0
    def inverse_kinematics(self, x, y):
        """
        This function will compute the required theta_0 and theta_1 angles to position the 
        foot to the point x, y. We will use an iterative solver to determine the angles.
        """
        error = Matrix([1e5, 1e5])
        (theta_0, theta_1) = self.get_joint_pos()

        while error.norm() > 0.1:
            (alpha_0, alpha_1) = self.compute_internal_angles(theta_0, theta_1)

            current_x = l_base / 2 + l1 * cos(theta_1) + l2 * cos(alpha_1)
            current_y = l1 * sin(theta_1) + l2 * sin(alpha_1)

            error = sympy.N(Matrix([x - current_x, y - current_y]))
            #J_inv_numerical = sympy.N(self.J_inv.subs([(theta0_sym, theta_0), (theta1_sym, theta_1), (alpha0_sym,alpha_0), (alpha1_sym, alpha_1)]))
            J_num = self.J.subs([(theta0_sym, theta_0), (theta1_sym, theta_1),
                                 (alpha0_sym, alpha_0), (alpha1_sym, alpha_1)])
            J_num = sympy.N(J_num)
            J_inv_numerical = J_num.pinv()
            d_theta = J_inv_numerical @ error * 0.05  #how much to move theta
            theta_0 = theta_0 + d_theta[0]  #update theta
            theta_1 = theta_1 + d_theta[1]
            print(error.norm())

        return (theta_0, theta_1)
示例#9
0
def sgc(omega=2 * sy.pi / 3, L=1, n_loops=3, n_steps=100):
    _, _, Ls = m_chi_Ls_from_omega_L(omega, L)
    omega_x = np.float(sy.N(omega))
    Ls_x = np.float(sy.N(Ls))
    s_array = s_samples(Ls=Ls_x, n_loops=n_loops, n_steps=n_steps)
    sgc_dx_dy_array = sgc_dx_dy(s_array, omega_x, Ls_x)
    x_array, y_array = sgc_integrate(s_array, sgc_dx_dy_array)
    return s_array, sgc_dx_dy_array, x_array, y_array
示例#10
0
 def acc_particle(self, x_app, y_app, z_app, t_app):
     vel = self.grad_phi(x_app, y_app, z_app, t_app)
     aeul = self.acc_euler(x_app, y_app, z_app, t_app)
     g2nd = self.grad_phi_2nd(x_app, y_app, z_app, t_app)
     ax = sp.N(aeul['x'] + vel['x'] * g2nd['xx'] + vel['y'] * g2nd['xy'] + vel['z'] * g2nd['xz'])
     ay = sp.N(aeul['y'] + vel['x'] * g2nd['xy'] + vel['y'] * g2nd['yy'] + vel['z'] * g2nd['yz'])
     az = sp.N(aeul['z'] + vel['x'] * g2nd['xz'] + vel['y'] * g2nd['yz'] + vel['z'] * g2nd['zz'])
     return {'x':ax, 'y':ay, 'z':az}
    def newton_raphson(self, xi, alpha=False):
        print()
        print()
        print("Newton Raphson :")
        print("_______________________")
        print()

        # creating the table format for printing
        table_format = ["i", "xi", "x(i+1)"]
        print("|{:>{tab}}|{:>{tab}}|{:>{tab}}|".format(
            *table_format, tab=2*self.tab))

        for i in range(self.itr_no+1):
            # evaluate f(xi) and f'(xi)
            fxi = float(sp.N(self.fx.subs(self.x, xi)))
            dfxi = float(sp.N(sp.diff(self.fx).subs(self.x, xi)))
            # if we want to add delta
            # delta δ = alpha - xi

            # estimate new value of x(i+1)
            xi_new = float(xi - (fxi/dfxi))
            

            if self.err_relative:
                ea = abs((xi_new - xi)/xi_new) if xi_new != 0 else 0.001
            else:
                ea = abs(xi_new - xi)

            # creating the data format for printing
            data = [i, xi, xi_new, ea]

            # check our stopping condition
            if ea <= self.ees:
                print("|{:>{tab}}|{:>{tab}}|{:>{tab}}|Ɛa ={:>{tab}} <=".format(
                    *data, tab=2*self.tab))
                print()
                print(f"root x{i+1} = {xi_new}")
                if alpha != False:
                    return i+1, xi_new,self.err_bound(alpha,xi)
                else:
                    return i+1, xi_new,False

            else:
                print("|{:>{tab}}|{:>{tab}}|{:>{tab}}|Ɛa ={:>{tab}} > ".format(
                    *data, tab=2*self.tab))

            # replace xi with x(i+1)
            xi = xi_new

        print()
        print("Max number of allowed iterations reached !!!")
        print(f"root x{i+1} = {xi_new}")
        print("_________________")
        if alpha != False:
            return i+1, xi_new,self.err_bound(alpha,xi)
        else:
            return i+1, xi_new,False
示例#12
0
def show_limit_estimate(f, r):

    display(Markdown("As the values of x get closer and closer to <br>"))
    display(Markdown("`" + str(r) + "`"))
    display(Markdown("the values f(x) seem to get close to somewhere around"))
    display(
        Markdown("`" +
                 str((sp.N(f(r - 0.001), 4) + sp.N(f(r + 0.001), 4)) / 2) +
                 "`"))
示例#13
0
 def getConfigurationMatrixCart(self):
     angle = sp.rad(self.angleCart)
     M = sp.Matrix([[sp.cos(angle), -sp.sin(angle), 0,
                     sp.N(self.x)],
                    [sp.sin(angle),
                     sp.cos(angle), 0,
                     sp.N(self.y)], [0, 0, 1, self.offset], [0, 0, 0, 1]])
     print("caa cart>>", M)
     return M
示例#14
0
def round_after_point(number, digits):
    if digits < 0:
        s = '%d' % decimal.Decimal(str(sympy.N(number)))
        if len(s) > -digits:
            return s[:digits] + '0' * (-digits)
        else:
            return '0'
    fmt = '%%.%df' % digits
    return fmt % decimal.Decimal(str(sympy.N(number)))
示例#15
0
 def circleDotProduct():
     f2c = sp.conjugate(f2)
     itR = sp.re(f1 * f2c * rho) / sp.S.Pi
     itI = sp.im(f1 * f2c * rho) / sp.S.Pi
     i1 = sp.N(sp.integrate(itR, (theta, 0, 2 * sp.pi), (rho, 0, 1)))
     i2 = sp.N(sp.integrate(itI, (theta, 0, 2 * sp.pi), (rho, 0, 1)))
     _rhs = i1 + sp.I * i2
     _lhs = dotInt
     return sp.Eq(_lhs, _rhs)
    def fixed_point(self, x1, x2=None):
        print()
        print()
        print("Fixed-Point :")
        print("_______________________")
        print()

        if x2:
            xi = (x1 + x2)/2
        else:
            xi = x1

        # evaluate g'(xi)
        dgx = float(sp.N(sp.diff(self.fx).subs(self.x, xi)))

        if dgx > 1:
            print(f"g'{xi} = {dgx} > 1    Divergence !!!")
            return -1, xi

        # creating the table format for printing
        table_format = ["i", "xi", "x(i+1)"]
        print("|{:>{tab}}|{:>{tab}}|{:>{tab}}|".format(
            *table_format, tab=2*self.tab))

        for i in range(1, self.itr_no+1):
            # estimate new value of x(i+1)
            xi_new = float(sp.N(self.fx.subs(self.x, xi)))

            if self.err_relative:
                ea = abs((xi_new - xi)/xi_new) if xi_new != 0 else 0.001
            else:
                ea = abs(xi_new - xi)

            # creating the data format for printing
            data = [i, xi, xi_new, ea]

            # check our stopping condition
            if ea <= self.ees:
                print("|{:>{tab}}|{:>{tab}}|{:>{tab}}|Ɛa ={:>{tab}} <=".format(
                    *data, tab=2*self.tab))
                print()
                print(f"root x{i} = {xi_new}")
                return i, xi_new
            else:
                print("|{:>{tab}}|{:>{tab}}|{:>{tab}}|Ɛa ={:>{tab}} > ".format(
                    *data, tab=2*self.tab))

            # replace xi with x(i+1)
            xi = xi_new

        print()
        print("Max number of allowed iterations reached !!!")
        print(f"root x{i} = {xi_new}")
        print("_________________")
        return i, xi_new
示例#17
0
def B_factor(input_chi_file, tau, metal, age):
    ####### Heirarchy is metallicity_-> age -> tau
    ####### Change chi to probabilites using sympy
    ####### for its arbitrary precission, must be done in loop
    dat = fits.open(input_chi_file)
    chi = []
    for i in range(len(metal)):
        chi.append(dat[i + 1].data)
    chi = np.array(chi)

    prob = []
    for i in range(len(metal)):
        preprob1 = []
        for ii in range(len(age)):
            preprob2 = []
            for iii in range(len(tau)):
                preprob2.append(sp.N(sp.exp(-chi[i][ii][iii] / 2)))
            preprob1.append(preprob2)
        prob.append(preprob1)

    ######## Marginalize over all tau
    ######## End up with age vs metallicity matricies
    ######## use unlogged tau
    ultau = np.append(0, np.power(10, tau[1:] - 9))
    M = []
    for i in range(len(metal)):
        A = []
        for ii in range(len(age)):
            T = []
            for iii in range(len(tau) - 1):
                T.append(
                    sp.N((ultau[iii + 1] - ultau[iii]) *
                         (prob[i][ii][iii] + prob[i][ii][iii + 1]) / 2))
            A.append(sp.mpmath.fsum(T))
        M.append(A)

    ######## Integrate over metallicity to get age prob
    ######## Then again over age to find normalizing coefficient
    preC1 = []
    for i in range(len(metal)):
        preC2 = []
        for ii in range(len(age) - 1):
            preC2.append(
                sp.N((age[ii + 1] - age[ii]) * (M[i][ii] + M[i][ii + 1]) / 2))
        preC1.append(sp.mpmath.fsum(preC2))

    preC3 = []
    for i in range(len(metal) - 1):
        preC3.append(
            sp.N((metal[i + 1] - metal[i]) * (preC1[i] + preC1[i + 1]) / 2))

    C = sp.mpmath.fsum(preC3)

    return C
    def err_bound(self, alpha, xi):
        delta = alpha - xi
        dfa = sp.diff(self.fx)
        ddfa = sp.diff(dfa)

        ddfa = float(sp.N(ddfa.subs(self.x, alpha)))
        dfa = float(sp.N(dfa.subs(self.x, alpha)))
        

        delta_new = ((-ddfa)/(2*dfa)) * (delta**2)
        return abs(delta_new)
示例#19
0
def q(x):
    c = x
    #res = ((x**51)-1)/(x-1)
    x = sp.Symbol('x')
    f = ((x**51) - 1) / (x - 1)
    g = ((50 * x**51) - (51 * x**50) + 1) / ((x - 1)**2)
    value = {x: c}
    f.evalf(subs=value)
    g.evalf(subs=value)
    der = sp.N(g, subs=value)
    res = sp.N(f, subs=value)
    return res, der
    def secant(self, xi, xi_1):
        print()
        print()
        print("Secant :")
        print("_______________________")
        print()

        # creating the table format for printing
        table_format = ["i","x(i-1)","x(i)", "x(i+1)"]
        print("|{:>{tab}}|{:>{tab}}|{:>{tab}}|{:>{tab}}|".format(*table_format, tab=2 * self.tab))

        # if self.fx.subs(self.x,xi) * self.fx.subs(self.x,xi_1) >= 0:
        #     print("Secant method won't work")
        #     return

        for i in range(self.itr_no+1):
            fxi = float(sp.N(self.fx.subs(self.x,xi)))
            fxi_1 = float(sp.N(self.fx.subs(self.x,xi_1)))

            #Computing the estimated root
            xi_new = float(xi - fxi * ((xi_1 - xi)/(fxi_1 - fxi)))

            if self.err_relative:
                ea = abs((xi_new - xi)/xi_new) if xi_new != 0 else 0.001
            else:
                ea = abs(xi_new - xi)

            # creating the data format for printing
            data = [i, xi_1, xi, xi_new, ea]

            # check our stopping condition
            if ea <= self.ees:
                print("|{:>{tab}}|{:>{tab}}|{:>{tab}}|{:>{tab}}|Ɛa ={:>{tab}} <=".format(*data, tab=2 * self.tab))
                print()
                print(f"root x{i + 1} = {xi_new}")
                return i+1, xi_new
            else:
                print("|{:>{tab}}|{:>{tab}}|{:>{tab}}|{:>{tab}}|Ɛa ={:>{tab}} > ".format(*data, tab=2 * self.tab))

            #Replacing values
            xi_1 = xi
            xi = xi_new

            # if xi_1 == xi:
            #     print("Can't Divide by Zero")
            #     return -1, xi

        print()
        print("Max number of allowed iterations reached !!!")
        print(f"root x{i + 1} = {xi_new}")
        print("_________________")
        return i+1, xi_new
示例#21
0
def Norm_P_specz(rshift, metal, age, chi):
    ####### Heirarchy is rshift_-> age -> metal
    ####### Change chi to probabilites using sympy
    ####### for its arbitrary precission, must be done in loop
    prob = []
    for i in range(len(rshift)):
        preprob1 = []
        for ii in range(len(age)):
            preprob2 = []
            for iii in range(len(metal)):
                preprob2.append(sp.N(sp.exp(-chi[i][ii][iii] / 2)))
            preprob1.append(preprob2)
        prob.append(preprob1)

    ######## Marginalize over all metal
    ######## End up with age vs rshift matricies
    R = []
    for i in range(len(rshift)):
        A = []
        for ii in range(len(age)):
            M = []
            for iii in range(len(metal) - 1):
                M.append(
                    sp.N((metal[iii + 1] - metal[iii]) *
                         (prob[i][ii][iii] + prob[i][ii][iii + 1]) / 2))
            A.append(sp.mpmath.fsum(M))
        R.append(A)

    ######## Integrate over age to get rshift prob
    ######## Then again over age to find normalizing coefficient
    preC1 = []
    for i in range(len(rshift)):
        preC2 = []
        for ii in range(len(age) - 1):
            preC2.append(
                sp.N((age[ii + 1] - age[ii]) * (R[i][ii] + R[i][ii + 1]) / 2))
        preC1.append(sp.mpmath.fsum(preC2))

    preC3 = []
    for i in range(len(rshift) - 1):
        preC3.append(
            sp.N((rshift[i + 1] - rshift[i]) * (preC1[i] + preC1[i + 1]) / 2))

    C = sp.mpmath.fsum(preC3)

    ######## Create normal prob grid
    P = []
    for i in range(len(rshift)):
        P.append(preC1[i] / C)

    return np.array(P).astype(np.float128)
def CovRel(v1, v2):
    euler = Rotate(v1[1], v1[2], v2[1], v2[2])
    alpha = euler[0]
    beta = euler[1]
    gamma = euler[2]
    print("Angles:", euler)

    unrot = UnrotCovRel(beta, v1[0], v2[0])
    #print("unrot", unrot)
    VarRot = sp.N(np.e**(2 * 1j * (alpha - gamma)) * unrot[0])
    #VarRot = sp.N(np.e**(2 * 1j* (alpha+gamma))*unrot[0])
    RelRot = sp.N(np.e**(2 * 1j * (-alpha - gamma)) * unrot[1])

    return VarRot, RelRot
示例#23
0
def two_dim(f, f2=None, xc=0.4, x=sympy.Symbol('x')):
    """
    Evaluate string `f` then integrate between 0 and 1.

    Populate a 2x2 matrix with the definite integral of `f` between
    [0, 1] (or `f` between [0, `xc`] + `f2` between [`xc`, 1]).  Requires
    MS = ['PTIB', 'PTPB'], and PTIB and PTPB global variables.  Integrals
    at each element depend on values in PTIB and PTPB.

    As `f` and `f2` will be useed with eval(), all variables in the string
    must be defined elsewhere except mi and mj which will be defined at each
    matrix element location.

    Parameters
    ----------
    f : ``str``
        String to be evaluated and then integrated between [0,1] (or [0, `xc`]
        if f2 is not None).
    f2 : ``str``, optional
        String to be evaluated and then integrated between [`xc`, 1] (default
        is none, i.e. this will not contribute).
    xc : [0, 1], optional
        Break point on the left of which `f` will be integrated and on the
        right of which `f2` will be integrated. (Default xc=0.4).
    `x`: sympy.Symbol
        Integrateion varibale Default x=sympy.Symbol('x').



    """
    #global A1
    #global A2

    if False:
        for drainage in MS:
            A = [[0, 0], [0, 0]]
            for i, mi in enumerate(eval(drainage)):
                for j, mj in enumerate(eval(drainage)):
                    if f2:

                        A[i][j] = sympy.N(
                            sympy.integrate(eval(f), (x, 0, xc)) +
                            sympy.integrate(eval(f2), (x, xc, 1.0)), 8)
                    else:
                        A[i][j] = sympy.N(sympy.integrate(eval(f), (x, 0, 1)),
                                          8)
            print(drainage)
            print('np.array(' + str(A) + ')')
    else:
        print('eval is disabled')
示例#24
0
    def update_scheme(self):
        try:
            # TODO: try to union with EntryExpr check
            h = sp.N(self.entries['h'].get())
            a = sp.N(self.entries['a'].get())

            if h > 0 and a > 0:
                koeff = min([100 / h, 200 / a])
                pix_h = max([2, floor(koeff * h)])
                pix_a = max([2, floor(koeff * a)])

                self.canvas.delete('all')
                self.create_scheme(pix_h, pix_a)
        except Exception:
            pass
示例#25
0
def draw_ball(ball, canvas, origin, factor, place_label=False):
    center = ball['center']
    height = ball['height']

    x = origin[0] + factor * sym.re(center)
    y = origin[1] - factor * sym.im(center)  # Flip coordinate system
    r = factor * height / 2
    #print '({0},{1},{2})'.format(x,y,r)

    draw_oval(canvas, x - r, y - r, x + r, y + r)

    if place_label:
        word = ball['word']
        label_text = word if len(word) > 0 else 'I'
        canvas.create_text(sym.N(x, prec), sym.N(y, prec), text=label_text)
def primero(f, n, a):
    resultado = 0
    for i in range(0, n + 1):
        derivada = f.diff(x, i)

        resultado += (sp.N(f, subs={x: a}) * (valor - a)**i) / (factorial(i))
    return resultado
示例#27
0
    def plot_autarky(self, lim=(0, 1)):
        # draw price lines only around the tangent spot
        price_line_length_per_x = (sp.N(self.ppf_slope.subs(
            {qx: self.autarky_qx})) ** 2 + 1) ** 0.5
        price_line_xrange = lim[1] / 3 / price_line_length_per_x
        price_line_range = (qx, self.autarky_qx - price_line_xrange,
                            self.autarky_qx + price_line_xrange)

        color = self.color_gen(self.rgb)

        autarky_plot = sp.plotting.plot(self.ppf, (qx, *lim), show=False,
                                        label=self.name + " ppf", line_color=next(color))
        further_plots = [
            sp.plotting.plot(self.indifference_curve, price_line_range, show=False,
                             label=self.name + " indifference curve", line_color=next(color)),
            sp.plotting.plot(self.autarky_price_line, price_line_range, show=False,
                             label=self.name + " price line", line_color=next(color)),
        ]
        for g in further_plots:
            autarky_plot.extend(g)

        autarky_plot.xlim = lim
        autarky_plot.ylim = lim
        autarky_plot.xlabel = "Q_" + self.product_x
        autarky_plot.ylabel = "Q_" + self.product_y
        autarky_plot.legend = True
        # plot.title = title + "(autarky)"

        return autarky_plot
示例#28
0
 def phi_t(self, x_app, y_app, z_app, t_app):
     return sp.N(self.f_phi_t.subs({
         x: x_app,
         y: y_app,
         z: z_app,
         t: t_app
     }))
def test_WignerDRecursion_accuracy():
    from sympy.physics.quantum.spin import WignerD as sympyWignerD
    """Eq. (29) of arxiv:1403.7698: d^{m',m}_{n}(β) = ϵ(m') ϵ(-m) H^{m',m}_{n}(β)"""
    def ϵ(m):
        m = np.asarray(m)
        eps = np.ones_like(m)
        eps[m >= 0] = (-1)**m[m >= 0]
        return eps

    ell_max = 4
    alpha, beta, gamma = 0.0, 0.1, 0.0
    hcalc = HCalculator(ell_max)
    Hnmpm = hcalc(np.cos(beta))
    max_error = 0.0
    # errors = np.empty(hcalc.nmpm_total_size)

    i = 0
    print()
    for n in range(hcalc.n_max + 1):
        print('Testing n={} compared to sympy'.format(n))
        for mp in range(-n, n + 1):
            for m in range(-n, n + 1):
                sympyd = sympy.re(
                    sympy.N(
                        sympyWignerD(n, mp, m, alpha, -beta, gamma).doit()))
                myd = ϵ(mp) * ϵ(-m) * Hnmpm[i]
                error = float(min(abs(sympyd + myd), abs(sympyd - myd)))
                assert error < 1e-14, "Testing Wigner d recursion: n={}, m'={}, m={}, v1={}, v2={}, error={}".format(
                    n, mp, m, sympyd, myd, error)
                max_error = max(error, max_error)
                # errors[i] = float(min(abs(sympyd+myd), abs(sympyd-myd)))
                # print("{:>5} {:>5} {:>5} {:24} {:24} {:24}".format(n, mp, m, float(sympyd), myd, errors[i]))
                i += 1

    print("Testing Wigner d recursion: max error = {}".format(max_error))
示例#30
0
    def subs_scal(self, scal, x, values):

        for idx1, var in enumerate(x):

            scal = scal.subs(var, values[idx1])

        return sy.N(scal)