示例#1
0
def calc(dc):
    p1 = sympy.integrate(sympy.pi * S(dc.u) ** 2, (x, 0, 1))
    p2 = sympy.integrate(sympy.pi * S(dc.v) ** 2, (x, 1, S(dc.d)))
    p3 = sympy.integrate(sympy.pi * S(dc.w) ** 2, (x, S(dc.d), S(dc.h)))
    m4 = sympy.integrate(sympy.pi * S(dc.z) ** 2, (x, S(dc.g), S(dc.h)))
    res = S(p1 + p2 + p3 - m4).n()
    return [res]
示例#2
0
文件: ode.py 项目: rikazry/compy
def separable_equation(g, h, hf = None):
    """
    dy/dx = g(x)*h(y)
    dy/h(y) = g(x)*dx
    """
    dy, dx = symbols('dy, dx')
    print '\nODE to solve:'
    pprint(Eq(dy/dx, g*h))
    pprint(Eq(dy/h, g*dx))
    print '\nintegrate both sides:'
    LHS, RHS = symbols('LHS, RHS')
    pprint(Eq(LHS, Integral(1/h,y)))
    H = integrate(1/h,y)
    pprint(Eq(LHS, H))
    pprint(Eq(RHS,Integral(g,x)))
    G = integrate(g, x)
    pprint(Eq(RHS, G))
    C = symbols('C')
    print '\nsolving LHS = RHS + C...'
    eq = Eq(H,G+C)
    pprint(eq)
    pprint(solve(eq, y))
    if hf:
        print '\nsolving ODE directly ...'
        pprint(dsolve(f(x).diff(x)-g*hf, f(x)))
示例#3
0
def test_integrate_poly_accurately():
    y = Symbol('y')
    assert integrate(x*sin(y), x) == x**2*sin(y)/2

    # when passed to risch_norman, this will be a CPU hog, so this really
    # checks, that integrated function is recognized as polynomial
    assert integrate(x**1000*sin(y), x) == x**1001*sin(y)/1001
示例#4
0
def test_issue841():
    from sympy import expand_mul
    from sympy.abc import k

    assert expand_mul(integrate(exp(-x ** 2) * exp(I * k * x), (x, -oo, oo))) == sqrt(pi) * exp(-k ** 2 / 4)
    a, d = symbols("a d", positive=True)
    assert expand_mul(integrate(exp(-a * x ** 2 + 2 * d * x), (x, -oo, oo))) == sqrt(pi) * exp(d ** 2 / a) / sqrt(a)
示例#5
0
def test_integrate_linearterm_pow():
    # check integrate((a*x+b)^c, x)  --  issue 3499
    y = Symbol('y', positive=True)
    # TODO: Remove conds='none' below, let the assumption take care of it.
    assert integrate(x**y, x, conds='none') == x**(y + 1)/(y + 1)
    assert integrate((exp(y)*x + 1/y)**(1 + sin(y)), x, conds='none') == \
        exp(-y)*(exp(y)*x + 1/y)**(2 + sin(y)) / (2 + sin(y))
示例#6
0
def test_singularities():
    assert integrate(1/x**2, (x, -oo, oo)) == oo
    assert integrate(1/x**2, (x, -1, 1)) == oo
    assert integrate(1/(x - 1)**2, (x, -2, 2)) == oo

    assert integrate(1/x**2, (x, 1, -1)) == -oo
    assert integrate(1/(x - 1)**2, (x, 2, -2)) == -oo
示例#7
0
def test_integrate_omit_var():
    y = Symbol('y')

    assert integrate(x) == x**2/2

    raises(ValueError, lambda: integrate(2))
    raises(ValueError, lambda: integrate(x*y))
示例#8
0
def test_piecewise_with_DiracDelta():
    d1 = DiracDelta(x - 1)
    assert integrate(d1, (x, -oo, oo)) == 1
    assert integrate(d1, (x, 0, 2)) == 1
    assert Piecewise((d1, Eq(x, 2)), (0, True)).integrate(x) == 0
    assert Piecewise((d1, x < 2), (0, True)).integrate(x) == Piecewise(
        (Heaviside(x - 1), x < 2), (1, True))
示例#9
0
def test_issue_8368():
    assert integrate(exp(-s*x)*cosh(x), (x, 0, oo)) == \
        Piecewise(
            (   pi*Piecewise(
                    (   -s/(pi*(-s**2 + 1)),
                        Abs(s**2) < 1),
                    (   1/(pi*s*(1 - 1/s**2)),
                        Abs(s**(-2)) < 1),
                    (   meijerg(
                            ((S(1)/2,), (0, 0)),
                            ((0, S(1)/2), (0,)),
                            polar_lift(s)**2),
                        True)
                ),
                And(
                    Abs(periodic_argument(polar_lift(s)**2, oo)) < pi,
                    cos(Abs(periodic_argument(polar_lift(s)**2, oo))/2)*sqrt(Abs(s**2)) - 1 > 0,
                    Ne(s**2, 1))
            ),
            (
                Integral(exp(-s*x)*cosh(x), (x, 0, oo)),
                True))
    assert integrate(exp(-s*x)*sinh(x), (x, 0, oo)) == \
        Piecewise(
            (   -1/(s + 1)/2 - 1/(-s + 1)/2,
                And(
                    Ne(1/s, 1),
                    Abs(periodic_argument(s, oo)) < pi/2,
                    Abs(periodic_argument(s, oo)) <= pi/2,
                    cos(Abs(periodic_argument(s, oo)))*Abs(s) - 1 > 0)),
            (   Integral(exp(-s*x)*sinh(x), (x, 0, oo)),
                True))
示例#10
0
def test_messy():
    from sympy import (laplace_transform, Si, Shi, Chi, atan, Piecewise,
                       acoth, E1, besselj, acosh, asin, And, re,
                       fourier_transform, sqrt)
    assert laplace_transform(Si(x), x, s) == ((-atan(s) + pi/2)/s, 0, True)

    assert laplace_transform(Shi(x), x, s) == (acoth(s)/s, 1, True)

    # where should the logs be simplified?
    assert laplace_transform(Chi(x), x, s) == \
        ((log(s**(-2)) - log((s**2 - 1)/s**2))/(2*s), 1, True)

    # TODO maybe simplify the inequalities?
    assert laplace_transform(besselj(a, x), x, s)[1:] == \
        (0, And(S(0) < re(a/2) + S(1)/2, S(0) < re(a/2) + 1))

    # NOTE s < 0 can be done, but argument reduction is not good enough yet
    assert fourier_transform(besselj(1, x)/x, x, s, noconds=False) == \
        (Piecewise((0, 4*abs(pi**2*s**2) > 1),
                   (2*sqrt(-4*pi**2*s**2 + 1), True)), s > 0)
    # TODO FT(besselj(0,x)) - conditions are messy (but for acceptable reasons)
    #                       - folding could be better

    assert integrate(E1(x)*besselj(0, x), (x, 0, oo), meijerg=True) == \
        log(1 + sqrt(2))
    assert integrate(E1(x)*besselj(1, x), (x, 0, oo), meijerg=True) == \
        log(S(1)/2 + sqrt(2)/2)

    assert integrate(1/x/sqrt(1 - x**2), x, meijerg=True) == \
        Piecewise((-acosh(1/x), 1 < abs(x**(-2))), (I*asin(1/x), True))
	def setThreshold(self):
		import sympy
		# f(x) is probability density of processing times 
		# Using Bounded Pareto,
			# f(x) = {0 if x < 0, main.customEquation if x >= 0}
		# Probability jobs will be in class 1, ie. their processing time will be between Lower and Threshold
		# Prob(Lower <= procTime <= Threshold) = integral{from L to T}f(x)dx >> 0.8 (should be very close to 1)
		# Most jobs will be small, only a few will be big

		# ???
		# lambda * integral{from L to U} x*f(x) dx < numServers

		#HOW TO FIND THRESHOLD
		# integral{from L to T} x*f(x)dx / integral{from L to U} x*f(x)dx = 0.8 (becasue 80% of jobs will be small)
		# solve for T
		x, L, U, T, alpha = sympy.symbols('x L U T alpha', real=True)
		
		numerator = sympy.integrate((x*BoundedParetoDist.Function), (x, L, T))
		denominator = sympy.integrate((x*BoundedParetoDist.Function), (x, L, U))
		expected = numerator/denominator

		#expected = expected.subs(dict(alpha=JobClass.BPArray[0], L=JobClass.BPArray[1], U=JobClass.BPArray[2]))
		expected = expected.subs([(alpha, JobClass.BPArray[0]), (L, JobClass.BPArray[1]), (U, JobClass.BPArray[2])])
		#print "expected subed"
		#print expected
		
		#Equate expected = 0.8, solve for T
		#thresholdRange = sympy.solve(sympy.Eq(expected, 0.8), T)
		#MachineClass.Threshold = thresholdRange[1] #set only positive number

		##FORCE THRESHOLD AS LOGICAL VALUE
		MachineClass.Threshold = 800000
		GUI.writeToConsole(self.master, "Class threshold = %s"%MachineClass.Threshold)
示例#12
0
def test_issue524():
    assert integrate(cos((n+1) * x), x)   == sin(x*(n+1)) / (n+1)
    assert integrate(cos((n-1) * x), x)   == sin(x*(n-1)) / (n-1)

    assert integrate(cos((n+1) * x) + cos((n-1) * x), x) == \
                                             sin(x*(n+1)) / (n+1)  + \
                                             sin(x*(n-1)) / (n-1)
示例#13
0
 def E(expr):
     res1 = integrate(expr*exponential(x, rate)*normal(y, mu1, sigma1),
                      (x, 0, oo), (y, -oo, oo), meijerg=True)
     res2 = integrate(expr*exponential(x, rate)*normal(y, mu1, sigma1),
                     (y, -oo, oo), (x, 0, oo), meijerg=True)
     assert expand_mul(res1) == expand_mul(res2)
     return res1
示例#14
0
def least_squares_orth(f, phi, Omega):
    """
    Same as least_squares, but for orthogonal
    basis such that one avoids calling up standard
    Gaussian elimination.
    """
    N = len(phi) - 1
    A = [0]*(N+1)       # plain list to hold symbolic expressions
    b = [0]*(N+1)
    x = sm.Symbol('x')
    print '...evaluating matrix...',
    for i in range(N+1):
        print '(%d,%d)' % (i, i)
        A[i] = sm.integrate(phi[i]**2, (x, Omega[0], Omega[1]))

        # Fallback on numerical integration if f*phi is too difficult
        # to integrate
        integrand = phi[i]*f
        I = sm.integrate(integrand,  (x, Omega[0], Omega[1]))
        if isinstance(I, sm.Integral):
            print 'numerical integration of', integrand
            integrand = sm.lambdify([x], integrand)
            I = sm.mpmath.quad(integrand, [Omega[0], Omega[1]])
        b[i] = I
    print 'A:\n', A, '\nb:\n', b
    c = [b[i]/A[i] for i in range(len(b))]
    print 'coeff:', c
    u = 0
    for i in range(len(phi)):
        u += c[i]*phi[i]
    # Alternative:
    # u = sum(c[i,0]*phi[i] for i in range(len(phi)))
    print 'approximation:', u
    return u
示例#15
0
文件: sympykern.py 项目: rajivsam/GPy
    def compute_psi_stats(self):
        # define some normal distributions
        mus = [sp.var("mu_%i" % i, real=True) for i in range(self.input_dim)]
        Ss = [sp.var("S_%i" % i, positive=True) for i in range(self.input_dim)]
        normals = [
            (2 * sp.pi * Si) ** (-0.5) * sp.exp(-0.5 * (xi - mui) ** 2 / Si) for xi, mui, Si in zip(self._sp_x, mus, Ss)
        ]

        # do some integration!
        # self._sp_psi0 = ??
        self._sp_psi1 = self._sp_k
        for i in range(self.input_dim):
            print "perfoming integrals %i of %i" % (i + 1, 2 * self.input_dim)
            sys.stdout.flush()
            self._sp_psi1 *= normals[i]
            self._sp_psi1 = sp.integrate(self._sp_psi1, (self._sp_x[i], -sp.oo, sp.oo))
            clear_cache()
        self._sp_psi1 = self._sp_psi1.simplify()

        # and here's psi2 (eek!)
        zprime = [sp.Symbol("zp%i" % i) for i in range(self.input_dim)]
        self._sp_psi2 = self._sp_k.copy() * self._sp_k.copy().subs(zip(self._sp_z, zprime))
        for i in range(self.input_dim):
            print "perfoming integrals %i of %i" % (self.input_dim + i + 1, 2 * self.input_dim)
            sys.stdout.flush()
            self._sp_psi2 *= normals[i]
            self._sp_psi2 = sp.integrate(self._sp_psi2, (self._sp_x[i], -sp.oo, sp.oo))
            clear_cache()
        self._sp_psi2 = self._sp_psi2.simplify()
示例#16
0
def test_piecewise_fold():
    p = Piecewise((x, x < 1), (1, 1 <= x))

    assert piecewise_fold(x*p) == Piecewise((x**2, x < 1), (x, 1 <= x))
    assert piecewise_fold(p + p) == Piecewise((2*x, x < 1), (2, 1 <= x))
    assert piecewise_fold(Piecewise((1, x < 0), (2, True))
                          + Piecewise((10, x < 0), (-10, True))) == \
        Piecewise((11, x < 0), (-8, True))

    p1 = Piecewise((0, x < 0), (x, x <= 1), (0, True))
    p2 = Piecewise((0, x < 0), (1 - x, x <= 1), (0, True))

    p = 4*p1 + 2*p2
    assert integrate(
        piecewise_fold(p), (x, -oo, oo)) == integrate(2*x + 2, (x, 0, 1))

    assert piecewise_fold(
        Piecewise((1, y <= 0), (-Piecewise((2, y >= 0)), True)
        )) == Piecewise((1, y <= 0), (-2, y >= 0))

    assert piecewise_fold(Piecewise((x, ITE(x > 0, y < 1, y > 1)))
        ) == Piecewise((x, ((x <= 0) | (y < 1)) & ((x > 0) | (y > 1))))

    a, b = (Piecewise((2, Eq(x, 0)), (0, True)),
        Piecewise((x, Eq(-x + y, 0)), (1, Eq(-x + y, 1)), (0, True)))
    assert piecewise_fold(Mul(a, b, evaluate=False)
        ) == piecewise_fold(Mul(b, a, evaluate=False))
示例#17
0
def case0(f, N=3):
    B = 1 - x ** 3
    dBdx = sm.diff(B, x)

    # Compute basis functions and their derivatives
    phi = {0: [x ** (i + 1) * (1 - x) for i in range(N + 1)]}
    phi[1] = [sm.diff(phi_i, x) for phi_i in phi[0]]

    def integrand_lhs(phi, i, j):
        return phi[1][i] * phi[1][j]

    def integrand_rhs(phi, i):
        return f * phi[0][i] - dBdx * phi[1][i]

    Omega = [0, 1]

    u_bar = solve(integrand_lhs, integrand_rhs, phi, Omega, verbose=True, numint=False)
    u = B + u_bar
    print "solution u:", sm.simplify(sm.expand(u))

    # Calculate analytical solution

    # Solve -u''=f by integrating f twice
    f1 = sm.integrate(f, x)
    f2 = sm.integrate(f1, x)
    # Add integration constants
    C1, C2 = sm.symbols("C1 C2")
    u_e = -f2 + C1 * x + C2
    # Find C1 and C2 from the boundary conditions u(0)=0, u(1)=1
    s = sm.solve([u_e.subs(x, 0) - 1, u_e.subs(x, 1) - 0], [C1, C2])
    # Form the exact solution
    u_e = -f2 + s[C1] * x + s[C2]
    print "analytical solution:", u_e
    # print 'error:', u - u_e  # many terms - which cancel
    print "error:", sm.expand(u - u_e)
示例#18
0
def main():
   intf = integrate( (x+2*y+3*z)**2 + (1**2+2**2+3**2), (x, -0.5, 0.5))
   intf = integrate(intf, (y, -0.5, 0.5))
   intf = integrate(intf, (z, -0.5, 0.5))
   #  the answers should be as shown:
   print "expected: 15.1666666666667   3.89444048184931"
   print "  actual: ", intf, " ", intf**(0.5)
示例#19
0
def least_squares(f, psi, Omega, symbolic=True, print_latex=False):
    """
    Given a function f(x,y) on a rectangular domain
    Omega=[[xmin,xmax],[ymin,ymax]],
    return the best approximation to f(x,y) in the space V
    spanned by the functions in the list psi.
    """
    N = len(psi) - 1
    A = sym.zeros((N+1, N+1))
    b = sym.zeros((N+1, 1))
    x, y = sym.symbols('x y')
    print '...evaluating matrix...'
    for i in range(N+1):
        for j in range(i, N+1):
            print '(%d,%d)' % (i, j)

            integrand = psi[i]*psi[j]
            if symbolic:
                I = sym.integrate(integrand,
                                 (x, Omega[0][0], Omega[0][1]),
                                 (y, Omega[1][0], Omega[1][1]))
            if not symbolic or isinstance(I, sym.Integral):
                # Could not integrate symbolically, use numerical int.
                print 'numerical integration of', integrand
                integrand = sym.lambdify([x,y], integrand)
                I = sym.mpmath.quad(integrand,
                                   [Omega[0][0], Omega[0][1]],
                                   [Omega[1][0], Omega[1][1]])
            A[i,j] = A[j,i] = I
        integrand = psi[i]*f
        if symbolic:
            I = sym.integrate(integrand,
                             (x, Omega[0][0], Omega[0][1]),
                             (y, Omega[1][0], Omega[1][1]))
        if not symbolic or isinstance(I, sym.Integral):
            # Could not integrate symbolically, use numerical int.
            print 'numerical integration of', integrand
            integrand = sym.lambdify([x,y], integrand)
            I = sym.mpmath.quad(integrand,
                               [Omega[0][0], Omega[0][1]],
                               [Omega[1][0], Omega[1][1]])
        b[i,0] = I
    print
    print 'A:\n', A, '\nb:\n', b
    if symbolic:
        c = A.LUsolve(b)  # symbolic solve
        # c is a sympy Matrix object, numbers are in c[i,0]
        c = [c[i,0] for i in range(c.shape[0])]
    else:
        c = sym.mpmath.lu_solve(A, b)  # numerical solve
    print 'coeff:', c

    u = sum(c[i]*psi[i] for i in range(len(psi)))
    print 'approximation:', u
    print 'f:', sym.expand(f)
    if print_latex:
        print sym.latex(A, mode='plain')
        print sym.latex(b, mode='plain')
        print sym.latex(c, mode='plain')
    return u, c
示例#20
0
def FEM_function_norms(N):

	h = 1.0/N
	print "N = ", N, " |  h = ", h

	# set up mesh points
	x = linspace(0,1,N+1)

	# set up function u(x)
	u = zeros(N+1)
	u[int(N/2)] = 1.0

	print "**** Analytical norms ****"
	import sympy as sym
	X = sym.Symbol('X')
	u1 = sym.Rational(1,h)*X - sym.Rational(1,h)*(0.5-h) 
	u2 = sym.Rational(-1,h)*X + sym.Rational(1,h)*(0.5+h) 

	L2 = sym.integrate(u1*u1,(X,0.5-h,0.5)) + sym.integrate(u2*u2,(X,0.5,0.5+h))
	print "L2: ", sqrt(float(L2))

	H1 = L2 + sym.integrate(sym.diff(u1,X)*sym.diff(u1,X),(X,0.5-h,0.5)) + sym.integrate(sym.diff(u1,X)*sym.diff(u1,X),(X,0.5,0.5+h))
	print "H1: ", sqrt(float(H1))

	print "**** Numerical norms ****"

	num_L2 = sum((u**2)/len(u))
	print  "L2: ", sqrt(num_L2) 

	dudx = (u[1:] - u[:-1])/(x[1]-x[0]) 
	num_H1 = sum(u[1:]**2 + dudx**2 )/len(u)
	print "H1: ", sqrt(num_H1) 

	return L2, H1
示例#21
0
 def __init__(self, cu,cv,la,mu):
   x, y = sympy.symbols('x y')
   self.cu=cu
   self.cv=cv
   self.L=la
   self.M=mu
   self.u=sympy.sympify(cu)
   self.v=sympy.sympify(cv)
   self.fu=eval("lambda x,y: numpy.array(["+cu[0]+","+cu[1]+"])")
   self.fv=eval("lambda x,y: numpy.array(["+cv[0]+","+cv[1]+"])")
   if self.u[0].is_polynomial(x,y) and self.u[1].is_polynomial(x,y):
     D0=sympy.polys.Poly(self.u[0],x,y).as_dict()
     D1=sympy.polys.Poly(self.u[1],x,y).as_dict()
     self.du=max(max(numpy.sum(list(D0.keys()),axis=1)),max(numpy.sum(list(D1.keys()),axis=1)))
   else:
     self.du=-1
   if self.v[0].is_polynomial(x,y) and self.v[1].is_polynomial(x,y):
     D0=sympy.polys.Poly(self.v[0],x,y).as_dict()
     D1=sympy.polys.Poly(self.v[1],x,y).as_dict()
     self.dv=max(max(numpy.sum(list(D0.keys()),axis=1)),max(numpy.sum(list(D1.keys()),axis=1)))
   else:
     self.dv=-1
   H=Hooke(self.L,self.M)
   gU=Gamma(self.u)
   gV=Gamma(self.v)
   self.I=sympy.integrate(sympy.integrate(gV.T*H*gU,(x,0,1)),(y,0,1))[0,0]
示例#22
0
def test_issue_841():
    a, b, c, d = symbols('a:d', positive=True, bounded=True)
    assert integrate(
        exp(-x**2 + I*c*x), x) == sqrt(pi)*erf(x - I*c/2)*exp(-c**S(2)/4)/2
    assert integrate(exp(a*x**2 + b*x + c), x) == \
          I*sqrt(pi)*erf(-I*x*sqrt(
              a) - I*b/(2*sqrt(a)))*exp(c)*exp(-b**2/(4*a))/(2*sqrt(a))
示例#23
0
def test_integrate_linearterm_pow():
    # check integrate((a*x+b)^c, x)  --  #400
    y = Symbol("y")
    assert integrate(x ** y, x) == x ** (y + 1) / (y + 1)
    assert integrate((exp(y) * x + 1 / y) ** (1 + sin(y)), x) == exp(-y) * (exp(y) * x + 1 / y) ** (2 + sin(y)) / (
        2 + sin(y)
    )
示例#24
0
def T_exact_symbolic(verbose=False):
    """Compute the exact solution formula via sympy."""
    # sol1: solution for t < t_star,
    # sol2: solution for t > t_star
    import sympy as sym
    T0 = sym.symbols('T0')
    k = sym.symbols('k', positive=True)
    # Piecewise linear T_sunction
    t, t_star, C0, C1 = sym.symbols('t t_star C0 C1')
    T_s = C0
    I = sym.integrate(sym.exp(k*t)*T_s, (t, 0, t))
    sol1 = T0*sym.exp(-k*t) + k*sym.exp(-k*t)*I
    sol1 = sym.simplify(sym.expand(sol1))
    if verbose:
        # Some debugging print
        print 'solution t < t_star:', sol1
        #print sym.latex(sol1)
    T_s = C1
    I = sym.integrate(sym.exp(k*t)*C0, (t, 0, t_star)) + \
        sym.integrate(sym.exp(k*t)*C1, (t, t_star, t))
    sol2 = T0*sym.exp(-k*t) + k*sym.exp(-k*t)*I
    sol2 = sym.simplify(sym.expand(sol2))
    if verbose:
        print 'solution t > t_star:', sol2
        #print sym.latex(sol2)

    # Convert to numerical functions
    exact0 = sym.lambdify([t, C0, k, T0],
                          sol1, modules='numpy')
    exact1 = sym.lambdify([t, C0, C1, t_star, k, T0],
                          sol2, modules='numpy')
    return exact0, exact1
示例#25
0
    def __init__(
            self,
            tau,  # A float
            start=None,
            ):
        print('''
tau={0}'''.format(tau))
        if start==None:
            start = tau -.05 + 2*tau
        x,lam = sympy.symbols('x lam'.split())
        self.tau = tau
        k = 0
        term = 1.0 + x*0   # \frac{1}{k!} * (-\frac{x}{lam})^k
        pk = 0             # sum_{n=0}^k term_k
        cum_prod = 1       # prod_{n=0}^k pk(tau)
        integral = 0       # integral_0^? rho(s) ds
        while tau*k < 1.0:
            pk += term              # Polynomial of x/lam
            pk_tau = pk.subs(x,tau) # Polynomial of tau/lam
            print('''  k={0}
  term={1}
  pk={2}
  '''.format(k, term, pk))
            if tau*(k+1) >= 1.0:
                d = 1.0 - tau*k
                integral += sympy.integrate(pk, (x, 0, d))/cum_prod
                break
            integral += sympy.integrate(pk, (x, 0, tau))/cum_prod
            # integral is a rational function of tau and lam
            cum_prod *= pk_tau      # Polynomial of tau/lam
            k += 1
            term *= -x/(k*lam)      # Monomial of x/lam
        print('''  cum_prod={2}  Solving
  {0}={1}'''.format(lam,integral.simplify(), cum_prod))
        self.eigenvalue = sympy.solve(lam-integral, lam)
示例#26
0
文件: tools.py 项目: juanre/econopy
def benefit_from_demand(x, p, demand):
    """Converts the demand curve to the benefit.  It assumes that the
    demand is a x=d(p) function, where the x= is implicit.

    >>> sp.var('x p')
    (x, p)
    >>> sp.simplify(benefit_from_demand(x, p, 10/p -1) -
    ...             10*sp.log(x+1))
    0
    >>> sp.simplify(benefit_from_demand(x, p, sp.Eq(x, 10/p -1)) -
    ...             10*sp.log(x+1))
    0
    >>> sp.simplify(benefit_from_demand(x, p, 100-p) -
    ...             (-x**2/2 + 100*x))
    0
    >>> benefit_from_demand(x, p, sp.Piecewise((0, p < 0),
    ...                                        (-p + 100, p <= 100),
    ...                                        (0, True)))
    -x**2/2 + 100*x
    """
    if isinstance(demand, sp.relational.Relational):
        return sp.integrate(sp.solve(demand, p)[0], (x, 0, x))
    substracting = sp.solve(demand-x, p)
    if substracting:
        toint = substracting[0]
    else:
        substracting = sp.solve(demand, p)
        if substracting:
            toint = substracting[0] - x
        else:
            return None

    return sp.integrate(toint, (x, 0, x))
示例#27
0
    def integrar(self):

        f = self.ui.lineEdit_int_funcion.text()

        f_var = [Symbol(self.ui.lineEdit_int_var_1.text()),
            Symbol(self.ui.lineEdit_int_var_2.text()),
            Symbol(self.ui.lineEdit_int_var_3.text())]

        f_min = [(self.ui.lineEdit_int_min_1.text()),
            (self.ui.lineEdit_int_min_2.text()),
            (self.ui.lineEdit_int_min_3.text())]

        f_max = [(self.ui.lineEdit_int_max_1.text()),
            (self.ui.lineEdit_int_max_2.text()),
            (self.ui.lineEdit_int_max_3.text())]

        for i in range(0, int(self.ui.spinBox_int.text())):
            if self.ui.radioButton_int_def.isChecked() is True:
                f = integrate(f, (f_var[i], f_min[i], f_max[i]))
                self.ui.label_int_solucion.setText(str(f))
                print (f)

            else:
                f = integrate(f, f_var[i])
                self.ui.label_int_solucion.setText(str(f))
                print (f)
示例#28
0
def test_issue_1791():
    z = Symbol("z", positive=True)
    assert integrate(exp(-log(x) ** 2), x) == pi ** (S(1) / 2) * erf(-S(1) / 2 + log(x)) * exp(S(1) / 4) / 2
    assert integrate(exp(log(x) ** 2), x) == -I * pi ** (S(1) / 2) * erf(I * log(x) + I / 2) * exp(-S(1) / 4) / 2
    assert integrate(exp(-z * log(x) ** 2), x) == pi ** (S(1) / 2) * erf(
        z ** (S(1) / 2) * log(x) - 1 / (2 * z ** (S(1) / 2))
    ) * exp(S(1) / (4 * z)) / (2 * z ** (S(1) / 2))
示例#29
0
def integrate_f_over_polygon_code(f):
    """Generate code that will integrate a function over a polygon

    Parameters
    ----------
    f : sympy expression
        Expression to be integrated over the polygon.

    Returns
    -------
    out : str
        Multiline string of function code

    """

    x, y, z=sympy.symbols('x,y,z')
    x0, x1, y0, y1, z0, z1=sympy.symbols('x0,x1,y0,y1,z0,z1')
    t = sympy.symbols('t')
    s2 = [(x, x0+t*(x1-x0)), (y, y0+t*(y1-y0)), (z, z0+t*(z1-z0))]

    ff = sympy.integrate(f,x)
    ff = ff.subs(s2)
    ff = sympy.integrate(ff, (t,0,1))
    ff *= (y1 - y0) #if integrating in y direction 1st then *-(x1-x0)

    ff = replace_x0_and_x1_with_vect(ff)

    template ="""def ifxy(pts):
    "Integrate f = {} over polygon"

    x, y, z = xyz_from_pts(pts, True)

    return np.sum({})"""

    return template.format(str(f), ff)
示例#30
0
 def __init__(self, cu,cv):
   x, y, z = sympy.symbols('x y z')
   self.cu=cu
   self.cv=cv
   self.u=sympy.Lambda((x,y,z),cu)
   self.v=sympy.Lambda((x,y,z),cv)
   self.fu=eval("lambda x,y,z: "+cu)
   self.fv=eval("lambda x,y,z: "+cv)
   if self.u.is_polynomial(x,y,z):
     D=sympy.polys.Poly(cu,x,y,z).as_dict()
     self.du=max(numpy.sum(list(D.keys()),axis=1))
   else:
     self.du=-1
   if self.v.is_polynomial(x,y,z):
     D=sympy.polys.Poly(cv,x,y,z).as_dict()
     self.dv=max(numpy.sum(list(D.keys()),axis=1))
   else:
     self.dv=-1
   self.I=sympy.integrate(
            sympy.integrate(
              sympy.integrate(
                sympy.diff(self.u(x,y,z),x)*sympy.diff(self.v(x,y,z),x)+
                sympy.diff(self.u(x,y,z),y)*sympy.diff(self.v(x,y,z),y)+
                sympy.diff(self.u(x,y,z),z)*sympy.diff(self.v(x,y,z),z),
                (x,0,1)),
              (y,0,1)),
            (z,0,1))
示例#31
0
def test_issue_4403_2():
    assert integrate(sqrt(-x**2 - 4), x) == \
        -2*atan(x/sqrt(-4 - x**2)) + x*sqrt(-4 - x**2)/2
示例#32
0
def test_issue_5178():
    assert integrate(sin(x)*f(y, z), (x, 0, pi), (y, 0, pi), (z, 0, pi)) == \
        2*Integral(f(y, z), (y, 0, pi), (z, 0, pi))
示例#33
0
def test_issue_5413():
    # Note that this is not the same as testing ratint() becuase integrate()
    # pulls out the coefficient.
    assert integrate(-a/(a**2 + x**2), x) == I*log(-I*a + x)/2 - I*log(I*a + x)/2
示例#34
0
def test_issue_4199():
    ypos = Symbol('y', positive=True)
    # TODO: Remove conds='none' below, let the assumption take care of it.
    assert integrate(exp(-I*2*pi*ypos*x)*x, (x, -oo, oo), conds='none') == \
        Integral(exp(-I*2*pi*ypos*x)*x, (x, -oo, oo))
示例#35
0
def test_issue_4517():
    assert integrate((sqrt(x) - x**3)/x**Rational(1, 3), x) == \
        6*x**Rational(7, 6)/7 - 3*x**Rational(11, 3)/11
示例#36
0
def test_issue_4376():
    n = Symbol('n', integer=True, positive=True)
    assert simplify(integrate(n*(x**(1/n) - 1), (x, 0, S.Half)) -
                (n**2 - 2**(1/n)*n**2 - n*2**(1/n))/(2**(1 + 1/n) + n*2**(1 + 1/n))) == 0
示例#37
0
def test_issue_4100():
    R = Symbol('R', positive=True)
    assert integrate(sqrt(R**2 - x**2), (x, 0, R)) == pi*R**2/4
示例#38
0
def test_integrate_DiracDelta_fails():
    # issue 6427
    assert integrate(integrate(integrate(
        DiracDelta(x - y - z), (z, 0, oo)), (y, 0, 1)), (x, 0, 1)) == S(1)/2
示例#39
0
def test_integrate_derivatives():
    assert integrate(Derivative(f(x), x), x) == f(x)
    assert integrate(Derivative(f(y), y), x) == x*Derivative(f(y), y)
示例#40
0
def test_integrate_returns_piecewise():
    assert integrate(x**y, x) == Piecewise(
        (log(x), Eq(y, -1)), (x**(y + 1)/(y + 1), True))
    assert integrate(x**y, y) == Piecewise(
        (y, Eq(log(x), 0)), (x**y/log(x), True))
    assert integrate(exp(n*x), x) == Piecewise(
        (x, Eq(n, 0)), (exp(n*x)/n, True))
    assert integrate(x*exp(n*x), x) == Piecewise(
        (x**2/2, Eq(n**3, 0)), ((x*n**2 - n)*exp(n*x)/n**3, True))
    assert integrate(x**(n*y), x) == Piecewise(
        (log(x), Eq(n*y, -1)), (x**(n*y + 1)/(n*y + 1), True))
    assert integrate(x**(n*y), y) == Piecewise(
        (y, Eq(n*log(x), 0)), (x**(n*y)/(n*log(x)), True))
    assert integrate(cos(n*x), x) == Piecewise(
        (x, Eq(n, 0)), (sin(n*x)/n, True))
    assert integrate(cos(n*x)**2, x) == Piecewise(
        (x, Eq(n, 0)), ((n*x/2 + sin(n*x)*cos(n*x)/2)/n, True))
    assert integrate(x*cos(n*x), x) == Piecewise(
        (x**2/2, Eq(n, 0)), (x*sin(n*x)/n + cos(n*x)/n**2, True))
    assert integrate(sin(n*x), x) == Piecewise(
        (0, Eq(n, 0)), (-cos(n*x)/n, True))
    assert integrate(sin(n*x)**2, x) == Piecewise(
        (0, Eq(n, 0)), ((n*x/2 - sin(n*x)*cos(n*x)/2)/n, True))
    assert integrate(x*sin(n*x), x) == Piecewise(
        (0, Eq(n, 0)), (-x*cos(n*x)/n + sin(n*x)/n**2, True))
    assert integrate(exp(x*y),(x,0,z)) == Piecewise( \
        (z, Eq(y,0)), (exp(y*z)/y - 1/y, True))
示例#41
0
def test_integrate_functions():
    # issue 4111
    assert integrate(f(x), x) == Integral(f(x), x)
    assert integrate(f(x), (x, 0, 1)) == Integral(f(x), (x, 0, 1))
    assert integrate(f(x)*diff(f(x), x), x) == f(x)**2/2
    assert integrate(diff(f(x), x) / f(x), x) == log(f(x))
示例#42
0
def test_issue_4052():
    f = S(1)/2*asin(x) + x*sqrt(1 - x**2)/2

    assert integrate(cos(asin(x)), x) == f
    assert integrate(sin(acos(x)), x) == f
示例#43
0
def test_issue_4516():
    assert integrate(2**x - 2*x, x) == 2**x/log(2) - x**2
示例#44
0
def test_improper_integral():
    assert integrate(log(x), (x, 0, 1)) == -1
    assert integrate(x**(-2), (x, 1, oo)) == 1
示例#45
0
def test_issue_3788():
    assert integrate(1/(1 + x**2), x) == atan(x)
示例#46
0
def test_issue_7450():
    ans = integrate(exp(-(1 + I)*x), (x, 0, oo))
    assert re(ans) == S.Half and im(ans) == -S.Half
示例#47
0
def test_transcendental_functions():
    assert integrate(LambertW(2*x), x) == \
        -x + x*LambertW(2*x) + x/LambertW(2*x)
示例#48
0
def test_issue_3952():
    f = sin(x)
    assert integrate(f, x) == -cos(x)
    raises(ValueError, lambda: integrate(f, 2*x))
示例#49
0
def test_issue_3686():  # remove this when fresnel itegrals are implemented
    from sympy import expand_func, fresnels
    assert expand_func(integrate(sin(x**2), x)) == \
        sqrt(2)*sqrt(pi)*fresnels(sqrt(2)*x/sqrt(pi))/2
示例#50
0
def test_issue_3740():
    f = 4*log(x) - 2*log(x)**2
    fid = diff(integrate(f, x), x)
    assert abs(f.subs(x, 42).evalf() - fid.subs(x, 42).evalf()) < 1e-10
示例#51
0
def test_issue_3618():
    assert integrate(pi*sqrt(x), x) == 2*pi*sqrt(x)**3/3
    assert integrate(pi*sqrt(x) + E*sqrt(x)**3, x) == \
        2*pi*sqrt(x)**3/3 + 2*E *sqrt(x)**5/5
示例#52
0
def test_integrate_units():
    m = units.m
    s = units.s
    assert integrate(x * m/s, (x, 1*s, 5*s)) == 12*m*s
示例#53
0
def test_issue_3560():
    assert integrate(sqrt(x)**3, x) == 2*sqrt(x)**5/5
    assert integrate(sqrt(x), x) == 2*sqrt(x)**3/3
    assert integrate(1/sqrt(x)**3, x) == -2/sqrt(x)
示例#54
0
def test_issue_3664():
    n = Symbol('n', integer=True, nonzero=True)
    assert integrate(-1./2 * x * sin(n * pi * x/2), [x, -2, 0]) == \
        2*cos(pi*n)/(pi*n)
    assert integrate(-Rational(1)/2 * x * sin(n * pi * x/2), [x, -2, 0]) == \
        2*cos(pi*n)/(pi*n)
示例#55
0
def test_multiple_integration():
    assert integrate((x**2)*(y**2), (x, 0, 1), (y, -1, 2)) == Rational(1)
    assert integrate((y**2)*(x**2), x, y) == Rational(1, 9)*(x**3)*(y**3)
    assert integrate(1/(x + 3)/(1 + x)**3, x) == \
        -S(1)/8*log(3 + x) + S(1)/8*log(1 + x) + x/(4 + 8*x + 4*x**2)
示例#56
0
def test_issue_3635():
    y = Symbol('y')
    assert integrate(x**2, y) == x**2*y
    assert integrate(x**2, (y, -1, 1)) == 2*x**2
示例#57
0
def test_issue_7130():
    i, L, a, b = symbols('i L a b')
    integrand = (cos(pi*i*x/L)**2 / (a + b*x)).rewrite(exp)
    assert x not in integrate(integrand, (x, 0, L)).free_symbols
示例#58
0
def test_issue_3532():
    assert integrate(exp(-x), (x, 0, oo)) == 1
示例#59
0
def test_limit_bug():
    z = Symbol('z', nonzero=True)
    assert integrate(sin(x*y*z), (x, 0, pi), (y, 0, pi)) == \
        (log(z**2) + 2*EulerGamma + 2*log(pi))/(2*z) - \
        (-log(pi*z) + log(pi**2*z**2)/2 + Ci(pi**2*z))/z + log(pi)/z
示例#60
0
def test_integration():
    assert integrate(0, (t, 0, x)) == 0
    assert integrate(3, (t, 0, x)) == 3*x
    assert integrate(t, (t, 0, x)) == x**2/2
    assert integrate(3*t, (t, 0, x)) == 3*x**2/2
    assert integrate(3*t**2, (t, 0, x)) == x**3
    assert integrate(1/t, (t, 1, x)) == log(x)
    assert integrate(-1/t**2, (t, 1, x)) == 1/x - 1
    assert integrate(t**2 + 5*t - 8, (t, 0, x)) == x**3/3 + 5*x**2/2 - 8*x
    assert integrate(x**2, x) == x**3/3
    assert integrate((3*t*x)**5, x) == (3*t)**5 * x**6 / 6

    b = Symbol("b")
    c = Symbol("c")
    assert integrate(a*t, (t, 0, x)) == a*x**2/2
    assert integrate(a*t**4, (t, 0, x)) == a*x**5/5
    assert integrate(a*t**2 + b*t + c, (t, 0, x)) == a*x**3/3 + b*x**2/2 + c*x