def daubechis(N):
	# make polynomial
	q_y = [sm.binomial(N-1+k,k) for k in reversed(range(N))]

	# get polynomial roots y[k]
	y = sm.mp.polyroots(q_y, maxsteps=200, extraprec=64)

	z = []
	for yk in y:
		# subustitute y = -1/4z + 1/2 - 1/4/z to factor f(y) = y - y[k]
		f = [sm.mpf('-1/4'), sm.mpf('1/2') - yk, sm.mpf('-1/4')]

		# get polynomial roots z[k]
		z += sm.mp.polyroots(f)

	# make polynomial using the roots within unit circle
	h0z = sm.sqrt('2')
	for zk in z:
		if sm.fabs(zk) < 1:
			h0z *= sympy.sympify('(z-zk)/(1-zk)').subs('zk',zk)

	# adapt vanising moments
	hz = (sympy.sympify('(1+z)/2')**N*h0z).expand()

	# get scaling coefficients
	return [sympy.re(hz.coeff('z',k)) for k in reversed(range(N*2))]
예제 #2
0
def test_mpmath_lambda():
    mpmath.mp.dps = 50
    sin02 = mpmath.mpf("0.19866933079506121545941262711838975037020672954020")
    f = lambdify(x, sin(x), "mpmath")
    prec = 1e-49  # mpmath precision is around 50 decimal places
    assert -prec < f(mpmath.mpf("0.2")) - sin02 < prec
    raises(TypeError, lambda: f(x))
예제 #3
0
def test_mpmath_lambda():
    mpmath.mp.dps = 50
    sin02 = mpmath.mpf("0.19866933079506121545941262711838975037020672954020")
    f = lambdify(x, sin(x), "mpmath")
    prec = 1e-49  # mpmath precision is around 50 decimal places
    assert -prec < f(mpmath.mpf("0.2")) - sin02 < prec
    raises(TypeError, lambda: f(x))
예제 #4
0
def _optimize_single(opt_params):
    '''mapped function for optimization of a single function in a single domain
    
    opt_params is a tuple (expression, subs, bound, use_basinhopping, use_corners)
    returns the interval
    '''

    (e, subs, bound, use_basinhopping, use_corners) = opt_params
    assert not (use_basinhopping and use_corners)

    rv = None
    e = _simplify_eq(e)

    if bound is None:
        rv = _eval_eq_direct(e, subs)
    else:
        under_approx = None

        if use_corners:
            under_approx = _eval_at_corners(e, subs)
        elif use_basinhopping:
            under_approx = _basinhopping(e, subs)
        else:
            under_approx = _eval_at_middle(e, subs)

        # under_approx param should be an array of size 1, since it gets updated
        rv = _eval_eq_bounded(e, subs, bound, [under_approx])

    # convert rv from interval to tuple (for pickling)
    return [float(mpf(rv.a)), float(mpf(rv.b))]
예제 #5
0
파일: sdcquad.py 프로젝트: dasmy/sdcquad
def uniform_nodes(n):
  """Return uniform nodes."""

  r = set()
  for i in range(n):
    r.add(mpmath.mpf('-1.0') + i * mpmath.mpf('2.0')/(n-1))

  return map_to_zero_one(r)
예제 #6
0
def mp_real(x):
    if type(x) == mpc:
        if x.imag == mpf(0):
            return mpf(x.real)
        else:
            raise ValueError
    else:
        return mpf(x)
예제 #7
0
파일: points.py 프로젝트: memmett/PyWENO
def gauss_lobatto(n):
  """Return Gauss-Lobatto nodes.

  Gauss-Lobatto nodes are roots of P'_{n-1}(x) and -1, 1.
  """

  x = sympy.var('x')
  p = legendre_poly(n-1).diff(x)
  r = find_roots(p)
  r = [mpmath.mpf('-1.0'), mpmath.mpf('1.0')] + r
  return sorted(r)
예제 #8
0
def gauss_lobatto(n):
    """Return Gauss-Lobatto nodes.

  Gauss-Lobatto nodes are roots of P'_{n-1}(x) and -1, 1.
  """

    x = sympy.var('x')
    p = legendre_poly(n - 1).diff(x)
    r = find_roots(p)
    r = [mpmath.mpf('-1.0'), mpmath.mpf('1.0')] + r
    return sorted(r)
예제 #9
0
def test_mod():
    assert mpf(234) % 1 == 0
    assert mpf(-3) % 256 == 253
    assert mpf(0.25) % 23490.5 == 0.25
    assert mpf(0.25) % -23490.5 == -23490.25
    assert mpf(-0.25) % 23490.5 == 23490.25
    assert mpf(-0.25) % -23490.5 == -0.25
    # Check that these cases are handled efficiently
    assert mpf('1e10000000000') % 1 == 0
    assert mpf('1.23e-1000000000') % 1 == mpf('1.23e-1000000000')
    # test __rmod__
    assert 3 % mpf('1.75') == 1.25
예제 #10
0
파일: evalf.py 프로젝트: smichr/sympy
def as_mpmath(x, prec, options):
    x = sympify(x)
    if isinstance(x, C.Zero):
        return mpf(0)
    if isinstance(x, C.Infinity):
        return mpf("inf")
    if isinstance(x, C.NegativeInfinity):
        return mpf("-inf")
    # XXX
    re, im, _, _ = evalf(x, prec, options)
    if im:
        return mpc(re or fzero, im)
    return mpf(re)
예제 #11
0
파일: sdcquad.py 프로젝트: dasmy/sdcquad
def gauss_lobatto_nodes(n):
  """Return Gauss-Lobatto nodes.

  Before mapping to [0,1], the nodes are: roots of :math:`P'_{n-1}(x)`
  and -1, 1.
  """

  x = sympy.var('x')
  p = legendre_poly(n-1).diff(x)
  r = find_roots(p)
  r = [mpmath.mpf('-1.0'), mpmath.mpf('1.0')] + r

  return map_to_zero_one(r)
예제 #12
0
def as_mpmath(x, prec, options):
    x = sympify(x)
    if isinstance(x, C.Zero):
        return mpf(0)
    if isinstance(x, C.Infinity):
        return mpf('inf')
    if isinstance(x, C.NegativeInfinity):
        return mpf('-inf')
    # XXX
    re, im, _, _ = evalf(x, prec, options)
    if im:
        return mpc(re or fzero, im)
    return mpf(re)
예제 #13
0
def mc_compute_stationary(P, precision=None, tol=None):
    n = P.shape[0]

    if precision is None:
        # Compute eigenvalues and eigenvectors
        eigvals, eigvecs = la.eig(P, left=True, right=False)

        # Find the index for unit eigenvalues
        index = np.where(abs(eigvals - 1.) < 1e-12)[0]

        # Pull out the eigenvectors that correspond to unit eig-vals
        uniteigvecs = eigvecs[:, index]

        stationary_dists = uniteigvecs / np.sum(uniteigvecs, axis=0)

    else:
        # Create a list to store eigvals
        stationary_dists_list = []
        if tol is None:
            # If tolerance isn't specified then use 2*precision
            tol = mp.mpf(2 * 10**(-precision + 1))

        with mp.workdps(precision):
            eigvals, eigvecs = mp.eig(mp.matrix(P), left=True, right=False)

            for ind, el in enumerate(eigvals):
                if el >= (mp.mpf(1) - mp.mpf(tol)) and el <= (mp.mpf(1) +
                                                              mp.mpf(tol)):
                    stationary_dists_list.append(eigvecs[ind, :])

            stationary_dists = np.asarray(stationary_dists_list).T
            stationary_dists = (stationary_dists /
                                sum(stationary_dists)).astype(np.float)

    # Check to make sure all of the elements of invar_dist are positive
    if np.any(stationary_dists < -1e-16):
        warn("Elements of your invariant distribution were negative; " +
             "Re-trying with additional precision")

        if precision is None:
            stationary_dists = mc_compute_stationary(P, precision=18, tol=tol)

        elif precision is not None:
            raise ValueError("Elements of your stationary distribution were" +
                             "negative.  Try computing with higher precision")

    # Since we will be accessing the columns of this matrix, we
    # might consider adding .astype(np.float, order='F') to make it
    # column major at beginning
    return stationary_dists.squeeze()
예제 #14
0
def mc_compute_stationary(P, precision=None, tol=None):
    n = P.shape[0]

    if precision is None:
        # Compute eigenvalues and eigenvectors
        eigvals, eigvecs = la.eig(P, left=True, right=False)

        # Find the index for unit eigenvalues
        index = np.where(abs(eigvals - 1.) < 1e-12)[0]

        # Pull out the eigenvectors that correspond to unit eig-vals
        uniteigvecs = eigvecs[:, index]

        stationary_dists = uniteigvecs/np.sum(uniteigvecs, axis=0)

    else:
        # Create a list to store eigvals
        stationary_dists_list = []
        if tol is None:
            # If tolerance isn't specified then use 2*precision
            tol = mp.mpf(2 * 10**(-precision + 1))

        with mp.workdps(precision):
            eigvals, eigvecs = mp.eig(mp.matrix(P), left=True, right=False)

            for ind, el in enumerate(eigvals):
                if el>=(mp.mpf(1)-mp.mpf(tol)) and el<=(mp.mpf(1)+mp.mpf(tol)):
                    stationary_dists_list.append(eigvecs[ind, :])

            stationary_dists = np.asarray(stationary_dists_list).T
            stationary_dists = (stationary_dists/sum(stationary_dists)).astype(np.float)


    # Check to make sure all of the elements of invar_dist are positive
    if np.any(stationary_dists < -1e-16):
        warn("Elements of your invariant distribution were negative; " +
              "Re-trying with additional precision")

        if precision is None:
            stationary_dists = mc_compute_stationary(P, precision=18, tol=tol)

        elif precision is not None:
            raise ValueError("Elements of your stationary distribution were" +
                             "negative.  Try computing with higher precision")

    # Since we will be accessing the columns of this matrix, we
    # might consider adding .astype(np.float, order='F') to make it
    # column major at beginning
    return stationary_dists.squeeze()
예제 #15
0
def test_mpmath_lambda():
    dps = mpmath.mp.dps
    mpmath.mp.dps = 50
    try:
        sin02 = mpmath.mpf("0.19866933079506121545941262711838975037020672954020")
        f = lambdify(x, sin(x), "mpmath")
        prec = 1e-49 # mpmath precision is around 50 decimal places
        assert -prec < f(mpmath.mpf("0.2")) - sin02 < prec
        try:
            f(x) # if this succeeds, it can't be a mpmath function
            assert False
        except TypeError:
            pass
    finally:
        mpmath.mp.dps = dps
예제 #16
0
 def genScaledVoltage(self):
     if self.isZeroT:
         self.Vq = self.Q*ELEC*self.V / HBAR
         self.scaledVolt = -1j*self.Vq
     else:
         self.Vq = self.Q*ELEC*self.V/(2*pi*BLTZMN*self.T)        
         self.scaledVolt = fmpc(self.gtot /mpf(2), - self.Vq )
예제 #17
0
 def f(i, j):
     gamDict = self.__genGammaDict(j, gDict)
     gamDict[-1] = mpf('0')
     def g(n):
         return gamDict[n]
     _g = vectorize(g)
     return _g(i)
예제 #18
0
def test_3250():
    from sympy.mpmath import mpf
    assert str(Float(mpf((1, 22, 2, 22)), '')) == '-88.000'
    assert Float('23.e3', '')._prec == 10
    assert Float('23e3', '')._prec == 20
    assert Float('23000', '')._prec == 20
    assert Float('-23000', '')._prec == 20
예제 #19
0
    def log(self):
        """
        Logaritmo de un intervalo: 'self.log()'

        NOTA: Si el intervalo contiene al 0, pero no es estrictamente negativo,
        se calcula el logaritmo de la intersecci\'on  del intervalo con el dominio
        natural del logaritmo, i.e., [0,+inf].
        """
        
        if 0 in self:

            domainNatural = Intervalo( 0, mpf('inf') )
            intervalRestricted = self.intersection( domainNatural )

            txt_warning = "\nWARNING: Interval {} contains 0 or negative numbers.\n".format(self)
            print txt_warning
            
            txt_warning = "Restricting to the intersection "\
                "with the natural domain of log(x), i.e. {}\n".format(intervalRestricted)
            print txt_warning
            
            return Intervalo( mp.log(intervalRestricted.lo), mp.log(intervalRestricted.hi) )

        elif 0 > self.hi:
            txt_error = 'Interval {} < 0\nlog(x) cannot be computed '\
                'for negative numbers.'.format(self)
            raise ValueError( txt_error )

        else:
            return Intervalo( mp.log(self.lo), mp.log(self.hi) )
예제 #20
0
 def genPrefactor(self):
     if self.isZeroT:
         self.prefac = fmfy(np.ones_like(self.parameters[:, 0]))
     else:
         fac = 2 * pi * BLTZMN * self.T / HBAR
         self.prefac = fexp(
             np.sum(self.g * self.parameters, axis=1) * fac / mpf(2))
예제 #21
0
    def log(self):
        """
        Logaritmo de un intervalo: 'self.log()'

        NOTA: Si el intervalo contiene al 0, pero no es estrictamente negativo,
        se calcula el logaritmo de la intersecci\'on  del intervalo con el dominio
        natural del logaritmo, i.e., [0,+inf].
        """

        if 0 in self:

            domainNatural = Intervalo(0, mpf('inf'))
            intervalRestricted = self.intersection(domainNatural)

            txt_warning = "\nWARNING: Interval {} contains 0 or negative numbers.\n".format(
                self)
            print txt_warning

            txt_warning = "Restricting to the intersection "\
                "with the natural domain of log(x), i.e. {}\n".format(intervalRestricted)
            print txt_warning

            return Intervalo(mp.log(intervalRestricted.lo),
                             mp.log(intervalRestricted.hi))

        elif 0 > self.hi:
            txt_error = 'Interval {} < 0\nlog(x) cannot be computed '\
                'for negative numbers.'.format(self)
            raise ValueError(txt_error)

        else:
            return Intervalo(mp.log(self.lo), mp.log(self.hi))
예제 #22
0
def test_math_lambda():
    mpmath.mp.dps = 50
    sin02 = mpmath.mpf("0.19866933079506121545941262711838975037020672954020")
    f = lambdify(x, sin(x), "math")
    prec = 1e-15
    assert -prec < f(0.2) - sin02 < prec
    raises(ValueError,"f(x)") # if this succeeds, it can't be a python math function
예제 #23
0
def test_3250():
    from sympy.mpmath import mpf
    assert str(Float(mpf((1,22,2,22)), '')) == '-88.000'
    assert Float('23.e3', '')._prec == 10
    assert Float('23e3', '')._prec == 20
    assert Float('23000', '')._prec == 20
    assert Float('-23000', '')._prec == 20
예제 #24
0
def test_mpmath_lambda():
    dps = mpmath.mp.dps
    mpmath.mp.dps = 50
    try:
        sin02 = mpmath.mpf(
            "0.19866933079506121545941262711838975037020672954020")
        f = lambdify(x, sin(x), "mpmath")
        prec = 1e-49  # mpmath precision is around 50 decimal places
        assert -prec < f(mpmath.mpf("0.2")) - sin02 < prec
        try:
            f(x)  # if this succeeds, it can't be a mpmath function
            assert False
        except TypeError:
            pass
    finally:
        mpmath.mp.dps = dps
예제 #25
0
def test_math_lambda():
    mpmath.mp.dps = 50
    sin02 = mpmath.mpf("0.19866933079506121545941262711838975037020672954020")
    f = lambdify(x, sin(x), "math")
    prec = 1e-15
    assert -prec < f(0.2) - sin02 < prec
    raises(ValueError, lambda: f(x))
예제 #26
0
 def __init__(self, parameters, maxParameter, 
              g, V, prefac, gtot,
              scaledVolt, T, Vq):
     self.Vq = Vq
     self.parameters = parameters
     self.V = V
     self.T = T
     self.isZeroT = mp.almosteq(self.T, mpf(0))
     self.scaledVolt = scaledVolt
     self.g = g
     self.maxParameter = maxParameter
     self.prefac = prefac
     self.gtot = gtot
     ### input check ###            
     if len(self.maxParameter.shape) == 1:
         self.maxParameter = self.maxParameter[newaxis,:]
     if len(self.prefac.shape) == 1:
         self.prefac = self.prefac[newaxis,:]
     if self.g.shape != self.parameters.shape or \
                 self.V.shape != self.scaledVolt.shape or \
                 self.maxParameter.shape[1] != self.parameters.shape[0]:
         
         raise ValueError
     if len(self.g.shape) == 1:
         self.g = self.g[:, newaxis]
         self.parameters = self.parameters[:, newaxis]
     self.prefac = self.prefac * np.power(self.maxParameter, 
                               -self.scaledVolt[...,newaxis])
예제 #27
0
 def _f(i, j):
     ldaDICT = dict((k, self.lda[k][j])  for k in self.wijnTerms)
     ldaDICT[-1] = mpf(0)
     def g(n): 
         return ldaDICT[n]
     _g = np.vectorize(g)
     return _g(i)
예제 #28
0
    def _eval_evalf(self, prec):
        """Evaluate this complex root to the given precision. """
        _prec, mp.prec = mp.prec, prec

        try:
            func = lambdify(self.poly.gen, self.expr)

            interval = self._get_interval()
            refined =  False

            while True:
                if self.is_real:
                    x0 = mpf(str(interval.center))
                else:
                    x0 = mpc(*map(str, interval.center))

                try:
                    root = findroot(func, x0)
                except ValueError:
                    interval = interval.refine()
                    refined = True
                    continue
                else:
                    if refined:
                        self._set_interval(interval)

                    break
        finally:
            mp.prec = _prec

        return Float._new(root.real._mpf_, prec) + I*Float._new(root.imag._mpf_, prec)
예제 #29
0
    def _eval_evalf(self, prec):
        """Evaluate this complex root to the given precision. """
        _prec, mp.prec = mp.prec, prec

        try:
            func = lambdify(self.poly.gen, self.expr)

            interval = self._get_interval()
            refined = False

            while True:
                if self.is_real:
                    x0 = mpf(str(interval.center))
                else:
                    x0 = mpc(*map(str, interval.center))

                try:
                    root = findroot(func, x0)
                except ValueError:
                    interval = interval.refine()
                    refined = True
                    continue
                else:
                    if refined:
                        self._set_interval(interval)

                    break
        finally:
            mp.prec = _prec

        return Float._new(root.real._mpf_, prec) + I*Float._new(root.imag._mpf_, prec)
예제 #30
0
 def __genGammaDict(self, j, gDict):
     if self.isZeroT:
         return dict((k, self.scaledVolt[j]**k /gDict[k]) for k in self.wijnTerms)
     else:
         fg = fgamma(self.scaledVolt[j])
         return dict((k, fgamma(self.scaledVolt[j] + mpf(str(k))) / \
                             (fg*gDict[k])) for k in self.wijnTerms)
예제 #31
0
def test_math_lambda():
    mpmath.mp.dps = 50
    sin02 = mpmath.mpf("0.19866933079506121545941262711838975037020672954020")
    f = lambdify(x, sin(x), "math")
    prec = 1e-15
    assert -prec < f(0.2) - sin02 < prec
    raises(TypeError, lambda: f(x))
예제 #32
0
 def genScaledVoltage(self):
     if self.isZeroT:
         self.Vq = self.Q * ELEC * self.V / HBAR
         self.scaledVolt = -1j * self.Vq
     else:
         self.Vq = self.Q * ELEC * self.V / (2 * pi * BLTZMN * self.T)
         self.scaledVolt = fmpc(self.gtot / mpf(2), -self.Vq)
예제 #33
0
파일: nodes.py 프로젝트: memmett/PyIPM
def clenshaw_curtis_nodes(n):
  """Return Clenshaw-Curtis nodes (actually returns n+1 nodes)."""

  r = set()
  for k in range(n+1):
    r.add(mpmath.cos(k*mpmath.pi/mpmath.mpf(n)))

  return sorted(r)
예제 #34
0
파일: sdcquad.py 프로젝트: dasmy/sdcquad
def clenshaw_curtis_nodes(n):
  """Return Clenshaw-Curtis nodes."""

  r = set()
  for i in range(n):
    r.add(mpmath.cos(i*mpmath.pi/mpmath.mpf(n-1)))

  return map_to_zero_one(r)
예제 #35
0
def test_3250():
    from sympy.mpmath import mpf

    assert str(Float(mpf((1, 22, 2, 22)), "")) == "-88.000"
    assert Float("23.e3", "")._prec == 10
    assert Float("23e3", "")._prec == 20
    assert Float("23000", "")._prec == 20
    assert Float("-23000", "")._prec == 20
예제 #36
0
 def get_real(y):
     if type(y) == mpc:
         if y.imag == mpf(0):
             return y.real
         else:
             raise ValueError
     else:
         return mp.mpf(y)
예제 #37
0
 def __genGammaDict(self, j, gDict):
     if self.isZeroT:
         return dict(
             (k, self.scaledVolt[j]**k / gDict[k]) for k in self.wijnTerms)
     else:
         fg = fgamma(self.scaledVolt[j])
         return dict((k, fgamma(self.scaledVolt[j] + mpf(str(k))) / \
                             (fg*gDict[k])) for k in self.wijnTerms)
예제 #38
0
        def f(i, j):
            gamDict = self.__genGammaDict(j, gDict)
            gamDict[-1] = mpf('0')

            def g(n):
                return gamDict[n]

            _g = vectorize(g)
            return _g(i)
예제 #39
0
def test_mpmath_lambda():
    f = lambdify(x, sin(x), "mpmath")
    prec = 1e-49 # mpmath precision is around 50 decimal places
    assert -prec < f(mpmath.mpf("0.2")) - sin02 < prec
    try:
        f(x) # if this succeeds, it can't be a mpmath function
        raise Exception
    except TypeError:
        pass
예제 #40
0
def test_sympy_lambda():
    mpmath.mp.dps = 50
    sin02 = mpmath.mpf("0.19866933079506121545941262711838975037020672954020")
    f = lambdify(x, sin(x), "sympy")
    assert f(x) == sin(x)
    prec = 1e-15
    assert -prec < f(Rational(1, 5)).evalf() - Float(str(sin02)) < prec
    # arctan is in numpy module and should not be available
    raises(NameError, lambda: lambdify(x, arctan(x), "sympy"))
예제 #41
0
def test_sympy_lambda():
    mpmath.mp.dps = 50
    sin02 = mpmath.mpf("0.19866933079506121545941262711838975037020672954020")
    f = lambdify(x, sin(x), "sympy")
    assert f(x) == sin(x)
    prec = 1e-15
    assert -prec < f(Rational(1, 5)).evalf() - Float(str(sin02)) < prec
    # arctan is in numpy module and should not be available
    raises(NameError, lambda: lambdify(x, arctan(x), "sympy"))
예제 #42
0
        def _f(i, j):
            ldaDICT = dict((k, self.lda[k][j]) for k in self.wijnTerms)
            ldaDICT[-1] = mpf(0)

            def g(n):
                return ldaDICT[n]

            _g = np.vectorize(g)
            return _g(i)
예제 #43
0
def test_mpmath_lambda():
    f = lambdify(x, sin(x), "mpmath")
    prec = 1e-49  # mpmath precision is around 50 decimal places
    assert -prec < f(mpmath.mpf("0.2")) - sin02 < prec
    try:
        f(x)  # if this succeeds, it can't be a mpmath function
        assert False
    except TypeError:
        pass
def update_maximum_error_points(list_a):
    n = len(list_a) - 1

    extreme_points = search_extreme_points(list_a)

    if len(extreme_points) == n + 1:
        return [sm.mpf(0.0)] + extreme_points
    else:
        raise Exception('[ERROR]number of extreme point ' + \
            str(n+2) + '->' + str(len(extreme_points)))
예제 #45
0
def test_number_precision():
    dps = mpmath.mp.dps
    mpmath.mp.dps = 50
    try:
        sin02 = mpmath.mpf("0.19866933079506121545941262711838975037020672954020")
        f = lambdify(x, sin02, "mpmath")
        prec = 1e-49 # mpmath precision is around 50 decimal places
        assert -prec < f(0) - sin02 < prec
    finally:
        mpmath.mp.dps = dps
예제 #46
0
def probability(n):
    """ Calculates the probability of an n-sided die to have all numbers
        in the list from 1 through n in a trial of n throws
        Input n : n-sided die
        Output prob : probability
    """

    if not isinstance(n, int):
        raise ValueError('Input not of integer instance')

    if n <= 0:
        raise ValueError('Input not a positive integer')

    exclusions_list = [(nC(n, r) * ((n - r)**n)) for r in range(n)]
    nr = reduce(operator.add,
                [x * y for x, y in izip(exclusions_list, cycle([1, -1]))])
    dr = n**n
    prob = mpmath.mpf(nr) / mpmath.mpf(dr)
    return prob
예제 #47
0
	def arithmeticalOperationX(self, i2, alpha, operation):
		""" Wrapper class for performing Fuzzy Arithmetic on X-mu Functions using SymPy/MPI. Primarily used as a private class, but could be used publicly.
		@param	i2	the target sympy formula.
		@param	alpha	the level on which to perform the operation.
		@param	operation	One of the following: +, -, *, /, **
		"""
		res = self.get_xequals().subs(ALPHA, float(alpha))
		res2 = i2.get_xequals().subs(ALPHA, float(alpha))
		if (not res.is_EmptySet) and (not res2.is_EmptySet):
			if (type(res) != FiniteSet) and (type(res2) != FiniteSet):
				result = eval("res.to_mpi() " + operation + " res2.to_mpi()")
			else:
				res_mpi = mpmath.mpi(res.inf, res.sup)
				res2_mpi = mpmath.mpi(res2.inf, res2.sup)
				result = eval("res_mpi " + operation + " res2_mpi")
			
			return BasicXmu(self.u, Interval(float(mpmath.mpf(result.a)), float(mpmath.mpf(result.b))))
		else:
			return None
예제 #48
0
    def __init__(self, input_parameters, V, Q, T):
        self.V, self.Q, self.T = V, mpf(Q), mpf(T)
########## Process input # Perform Sanity Checks ###########
        for i, j in input_parameters.items():
            if not isinstance(j, list):
                raise ValueError
            self.input_parameters[i] = np.asarray(j)
        if len(set(map(len, input_parameters.values()))) > 1:
            raise ValueError
        if not isinstance(self.V, np.ndarray) or not isinstance(self.V, list):
            self.V = np.array([self.V]).ravel()
        self.isZeroT = mp.almosteq(self.T, mpf(0))
########### Restructure distance and voltage, if necessary
        if len(self.input_parameters["x"].shape) == 1:
            self.input_parameters["x"] = self.input_parameters["x"][:,newaxis]
########### Generate parameters
        self.gtot = mp.fsum(self.input_parameters["g"])
        self.genParameters()
        self.genScaledVoltage()
예제 #49
0
    def _eval_evalf(self, prec):
        """Evaluate this complex root to the given precision. """
        with workprec(prec):
            g = self.poly.gen
            if not g.is_Symbol:
                d = Dummy('x')
                func = lambdify(d, self.expr.subs(g, d))
            else:
                func = lambdify(g, self.expr)

            interval = self._get_interval()
            if not self.is_real:
                # For complex intervals, we need to keep refining until the
                # imaginary interval is disjunct with other roots, that is,
                # until both ends get refined.
                ay = interval.ay
                by = interval.by
                while interval.ay == ay or interval.by == by:
                    interval = interval.refine()

            while True:
                if self.is_real:
                    x0 = mpf(str(interval.center))
                else:
                    x0 = mpc(*map(str, interval.center))
                try:
                    root = findroot(func, x0, verify=False)
                    # If the (real or complex) root is not in the 'interval',
                    # then keep refining the interval. This happens if findroot
                    # accidentally finds a different root outside of this
                    # interval because our initial estimate 'x0' was not close
                    # enough.
                    if self.is_real:
                        a = mpf(str(interval.a))
                        b = mpf(str(interval.b))
                        if a == b:
                            root = a
                            break
                        if not (a < root < b):
                            raise ValueError("Root not in the interval.")
                    else:
                        ax = mpf(str(interval.ax))
                        bx = mpf(str(interval.bx))
                        ay = mpf(str(interval.ay))
                        by = mpf(str(interval.by))
                        if ax == bx and ay == by:
                            root = ax + S.ImaginaryUnit * by
                            break
                        if not (ax < root.real < bx and ay < root.imag < by):
                            raise ValueError("Root not in the interval.")
                except ValueError:
                    interval = interval.refine()
                    continue
                else:
                    break

        return Float._new(root.real._mpf_,
                          prec) + I * Float._new(root.imag._mpf_, prec)
예제 #50
0
    def __pow__(self, exponent):
        """
        Se calcula la potencia de un intervalo; operador '**'
        UNDER TESTING
        """
        if isinstance(exponent, Intervalo):  # exponent is an interval

            if exponent.lo == exponent.hi:  # exponent is a thin interval
                return self**exponent.lo

            else:  # exponent is a generic interval
                return (exponent * self.log()).exp()

        else:  # exponent is a number (int, float, mpf, ...)

            if exponent == int(exponent):  # exponent is an integer

                if exponent >= 0:
                    if exponent % 2 == 0:  # even exponent
                        return Intervalo((self.mig())**exponent,
                                         (self.mag())**exponent)

                    else:  # odd exponent
                        return Intervalo(self.lo**exponent, self.hi**exponent)

                else:  # exponent < 0
                    return (self**(-exponent)).reciprocal()

            else:
                # exponent is a generic float
                if exponent >= 0:
                    if 0 in self:
                        domainNatural = Intervalo(0, mpf('inf'))
                        intervalRestricted = self.intersection(domainNatural)

                        txt_warning = "\nWARNING: Interval {} contains 0.\n".format(
                            self)
                        print txt_warning

                        txt_warning = "Restricting to the intersection "\
                              "with the natural domain of **, i.e. {}\n".format(intervalRestricted)
                        print txt_warning

                        return Intervalo(0, self.hi**exponent)

                    elif 0 > self:
                        raise ValueError(
                            "negative interval can not be raised to a fractional power"
                        )

                    else:
                        return Intervalo(self.lo**exponent, self.hi**exponent)

                else:
                    return (self**(-exponent)).reciprocal()
예제 #51
0
    def _eval_evalf(self, prec):
        """Evaluate this complex root to the given precision. """
        _prec, mp.prec = mp.prec, prec

        try:
            func = lambdify(self.poly.gen, self.expr)

            interval = self._get_interval()
            if not self.is_real:
                # For complex intervals, we need to keep refining until the
                # imaginary interval is disjunct with other roots, that is,
                # until both ends get refined.
                ay = interval.ay
                by = interval.by
                while interval.ay == ay or interval.by == by:
                    interval = interval.refine()

            while True:
                if self.is_real:
                    x0 = mpf(str(interval.center))
                else:
                    x0 = mpc(*map(str, interval.center))

                try:
                    root = findroot(func, x0)
                    # If the (real or complex) root is not in the 'interval',
                    # then keep refining the interval. This happens if findroot
                    # accidentally finds a different root outside of this
                    # interval because our initial estimate 'x0' was not close
                    # enough.
                    if self.is_real:
                        a = mpf(str(interval.a))
                        b = mpf(str(interval.b))
                        # This is needed due to the bug #3364:
                        a, b = min(a, b), max(a, b)
                        if not (a < root < b):
                            raise ValueError("Root not in the interval.")
                    else:
                        ax = mpf(str(interval.ax))
                        bx = mpf(str(interval.bx))
                        ay = mpf(str(interval.ay))
                        by = mpf(str(interval.by))
                        # This is needed due to the bug #3364:
                        ax, bx = min(ax, bx), max(ax, bx)
                        ay, by = min(ay, by), max(ay, by)
                        if not (ax < root.real < bx and ay < root.imag < by):
                            raise ValueError("Root not in the interval.")
                except ValueError:
                    interval = interval.refine()
                    continue
                else:
                    break
        finally:
            mp.prec = _prec

        return Float._new(root.real._mpf_,
                          prec) + I * Float._new(root.imag._mpf_, prec)
예제 #52
0
def sympy2mpmath(value, prec=None):
    if prec is None:
        from mathics.builtin.numeric import machine_precision
        prec = machine_precision
    value = value.n(dps(prec))
    if value.is_real:
        return mpmath.mpf(value)
    elif value.is_number:
        return mpmath.mpc(*value.as_real_imag())
    else:
        return None
예제 #53
0
def test_lambdify():
    mpmath.mp.dps = 16
    sin02 = mpmath.mpf("0.198669330795061215459412627")
    f = lambdify(x, sin(x), "numpy")
    prec = 1e-15
    assert -prec < f(0.2) - sin02 < prec
    try:
        f(x)  # if this succeeds, it can't be a numpy function
        assert False
    except AttributeError:
        pass
예제 #54
0
def test_number_precision():
    dps = mpmath.mp.dps
    mpmath.mp.dps = 50
    try:
        sin02 = mpmath.mpf(
            "0.19866933079506121545941262711838975037020672954020")
        f = lambdify(x, sin02, "mpmath")
        prec = 1e-49  # mpmath precision is around 50 decimal places
        assert -prec < f(0) - sin02 < prec
    finally:
        mpmath.mp.dps = dps
예제 #55
0
    def confidence(s, p):
        """Return a symmetric (p*100)% confidence interval. For example,
        p=0.95 gives a 95% confidence interval. Currently this function
        only handles numerical values except in the trivial case p=1.

        For example, one standard deviation:

            >>> from sympy.statistics import Normal
            >>> N = Normal(0, 1)
            >>> N.confidence(0.68)
            (-0.994457883209753, 0.994457883209753)
            >>> N.probability(*_).evalf()
            0.680000000000000

        Two standard deviations:

            >>> N = Normal(0, 1)
            >>> N.confidence(0.95)
            (-1.95996398454005, 1.95996398454005)
            >>> N.probability(*_).evalf()
            0.950000000000000

        """

        if p == 1:
            return (-oo, oo)

        if p > 1:
            raise ValueError("p cannot be greater than 1")

        # In terms of n*sigma, we have n = sqrt(2)*ierf(p). The inverse
        # error function is not yet implemented in SymPy but can easily be
        # computed numerically

        from sympy.mpmath import mpf, erfinv

        # calculate y = ierf(p) by solving erf(y) - p = 0
        y = erfinv(mpf(p))
        t = Float(str(mpf(float(s.sigma)) * mpf(2)**0.5 * y))
        mu = s.mu.evalf()
        return (mu - t, mu + t)
예제 #56
0
    def __init__(self, input_parameters, V, Q, T):
        self.V, self.Q, self.T = V, mpf(Q), mpf(T)
        ########## Process input # Perform Sanity Checks ###########
        for i, j in input_parameters.items():
            if not isinstance(j, list):
                raise ValueError
            self.input_parameters[i] = np.asarray(j)
        if len(set(map(len, input_parameters.values()))) > 1:
            raise ValueError
        if not isinstance(self.V, np.ndarray) or not isinstance(self.V, list):
            self.V = np.array([self.V]).ravel()
        self.isZeroT = mp.almosteq(self.T, mpf(0))
        ########### Restructure distance and voltage, if necessary
        if len(self.input_parameters["x"].shape) == 1:
            self.input_parameters["x"] = self.input_parameters["x"][:, newaxis]


########### Generate parameters
        self.gtot = mp.fsum(self.input_parameters["g"])
        self.genParameters()
        self.genScaledVoltage()
예제 #57
0
        def f(t):
            re, im, re_acc, im_acc = evalf(func, mp.prec, {'subs': {x: t}})

            have_part[0] = re or have_part[0]
            have_part[1] = im or have_part[1]

            max_real_term[0] = max(max_real_term[0], fastlog(re))
            max_imag_term[0] = max(max_imag_term[0], fastlog(im))

            if im:
                return mpc(re or fzero, im)
            return mpf(re or fzero)