• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python numbers.dps函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中mathics.core.numbers.dps函数的典型用法代码示例。如果您正苦于以下问题:Python dps函数的具体用法?Python dps怎么用?Python dps使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了dps函数的17个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: do_compare

    def do_compare(self, l1, l2):
        if l1.same(l2):
            return True
        elif l1 == Symbol('System`True') and l2 == Symbol('System`False'):
            return False
        elif l1 == Symbol('System`False') and l2 == Symbol('System`True'):
            return False
        elif isinstance(l1, String) and isinstance(l2, String):
            return False
        elif l1.has_form('List', None) and l2.has_form('List', None):
            if len(l1.leaves) != len(l2.leaves):
                return False
            for item1, item2 in zip(l1.leaves, l2.leaves):
                result = self.do_compare(item1, item2)
                if not result:
                    return result
            return True

        l1_sympy = l1.to_sympy()
        l2_sympy = l2.to_sympy()

        if l1_sympy is None or l2_sympy is None:
            return None
        if l1_sympy.is_number and l2_sympy.is_number:
            # assert min_prec(l1, l2) is None
            prec = 64  # TODO: Use $MaxExtraPrecision
            if l1_sympy.n(dps(prec)) == l2_sympy.n(dps(prec)):
                return True
            return False
        else:
            return None
开发者ID:mathics,项目名称:Mathics,代码行数:31,代码来源:comparison.py


示例2: apply

    def apply(self, items, evaluation):
        'Times[items___]'

        #TODO: Clean this up and optimise it        

        items = items.numerify(evaluation).get_sequence()
        number = (sympy.Integer(1), sympy.Integer(0))
        leaves = []

        prec = min_prec(*items)
        is_real = all([not isinstance(i, Complex) for i in items])

        for item in items:
            if isinstance(item, Number):
                if isinstance(item, Complex):
                    sym_real, sym_imag = item.real.to_sympy(), item.imag.to_sympy()
                else:
                    sym_real, sym_imag = item.to_sympy(), sympy.Integer(0)

                if prec is not None:
                    sym_real = sym_real.n(dps(prec))
                    sym_imag = sym_imag.n(dps(prec))

                if sym_real.is_zero and sym_imag.is_zero and prec is None:
                    return Integer('0')
                number = (number[0]*sym_real - number[1]*sym_imag, number[0]*sym_imag + number[1]*sym_real)
            elif leaves and item == leaves[-1]:
                leaves[-1] = Expression('Power', leaves[-1], Integer(2))
            elif leaves and item.has_form('Power', 2) and leaves[-1].has_form('Power', 2) and item.leaves[0].same(leaves[-1].leaves[0]):
                leaves[-1].leaves[1] = Expression('Plus', item.leaves[1], leaves[-1].leaves[1])
            elif leaves and item.has_form('Power', 2) and item.leaves[0].same(leaves[-1]):
                leaves[-1] = Expression('Power', leaves[-1], Expression('Plus', item.leaves[1], Integer(1)))
            elif leaves and leaves[-1].has_form('Power', 2) and leaves[-1].leaves[0].same(item):
                leaves[-1] = Expression('Power', item, Expression('Plus', Integer(1), leaves[-1].leaves[1]))
            else:
                leaves.append(item)
        if number == (1, 0):
            number = None
        elif number == (-1, 0) and leaves and leaves[0].has_form('Plus', None):
            leaves[0].leaves = [Expression('Times', Integer(-1), leaf) for leaf in leaves[0].leaves]
            number = None

        if number is not None:
            if number[1].is_zero and is_real:
                leaves.insert(0, Number.from_mp(number[0], prec))
            elif number[1].is_zero and number[1].is_Integer and prec is None:
                leaves.insert(0, Number.from_mp(number[0], prec))
            else:
                leaves.insert(0, Complex(from_sympy(number[0]), from_sympy(number[1]), prec))

        if not leaves:
            return Integer(1)
        elif len(leaves) == 1:
            return leaves[0]
        else:
            return Expression('Times', *leaves)
开发者ID:0xffea,项目名称:Mathics,代码行数:56,代码来源:arithmetic.py


示例3: apply_makeboxes

    def apply_makeboxes(self, expr, n, f, evaluation):
        '''MakeBoxes[BaseForm[expr_, n_],
            f:StandardForm|TraditionalForm|OutputForm]'''

        base = n.get_int_value()

        if base <= 0:
            evaluation.message('BaseForm', 'intpm', expr, n)
            return

        if not (isinstance(expr, Integer) or isinstance(expr, Real)):
            return Expression("MakeBoxes", expr, f)

        p = dps(expr.get_precision()) if isinstance(expr, Real) else 0

        try:
            val = convert_base(expr.get_real_value(), base, p)
        except ValueError:
            return evaluation.message('BaseForm', 'basf', n)

        if f.get_name() == 'System`OutputForm':
            return from_python("%s_%d" % (val, base))
        else:
            return Expression(
                'SubscriptBox', from_python(val), from_python(base))
开发者ID:ashtonbaker,项目名称:Mathics,代码行数:25,代码来源:numeric.py


示例4: apply_complex

    def apply_complex(self, x, evaluation):
        'Precision[x_Complex]'

        if x.is_inexact():
            return Real(dps(x.get_precision()))
        else:
            return Symbol('Infinity')
开发者ID:kirpit,项目名称:Mathics,代码行数:7,代码来源:numeric.py


示例5: apply

    def apply(self, z, evaluation):
        'Precision[z_]'

        if not z.is_inexact():
            return Symbol('Infinity')
        elif z.to_sympy().is_zero:
            return Real(0)
        else:
            return Real(dps(z.get_precision()))
开发者ID:Piruzzolo,项目名称:Mathics,代码行数:9,代码来源:numeric.py


示例6: do_compare

def do_compare(l1, l2):
    if l1.same(l2):
        return True
    elif isinstance(l1, String) and isinstance(l2, String):
        return False
    elif l1.to_sympy().is_number and l2.to_sympy().is_number:
        #assert min_prec(l1, l2) is None
        prec = 64       #TODO: Use $MaxExtraPrecision
        if l1.to_sympy().n(dps(prec)) == l2.to_sympy().n(dps(prec)):
           return True
        return False
    elif l1.has_form('List', None) and l2.has_form('List', None):
        if len(l1.leaves) != len(l2.leaves):
            return False
        for item1, item2 in zip(l1.leaves, l2.leaves):
            result = do_compare(item1, item2)
            if not result:
                return result
        return True
    else:
        return None
开发者ID:chid,项目名称:Mathics,代码行数:21,代码来源:comparison.py


示例7: apply

    def apply(self, f, xs, evaluation):
        'Integrate[f_, xs__]'

        f_sympy = f.to_sympy()
        if f_sympy is None or isinstance(f_sympy, SympyExpression):
            return
        xs = xs.get_sequence()
        vars = []
        prec = None
        for x in xs:
            if x.has_form('List', 3):
                x, a, b = x.leaves
                prec_a = a.get_precision()
                prec_b = b.get_precision()
                if prec_a is not None and prec_b is not None:
                    prec_new = min(prec_a, prec_b)
                    if prec is None or prec_new < prec:
                        prec = prec_new
                a = a.to_sympy()
                b = b.to_sympy()
                if a is None or b is None:
                    return
            else:
                a = b = None
            if not x.get_name():
                evaluation.message('Integrate', 'ilim')
                return
            x = x.to_sympy()
            if x is None:
                return
            if a is None or b is None:
                vars.append(x)
            else:
                vars.append((x, a, b))
        try:
            result = sympy.integrate(f_sympy, *vars)
        except sympy.PolynomialError:
            return
        except ValueError:
            # e.g. ValueError: can't raise polynomial to a negative power
            return
        except NotImplementedError:
            # e.g. NotImplementedError: Result depends on the sign of
            # -sign(_Mathics_User_j)*sign(_Mathics_User_w)
            return

        if prec is not None and isinstance(result, sympy.Integral):
            # TODO MaxExtaPrecision -> maxn
            result = result.evalf(dps(prec))
        result = from_sympy(result)
        return result
开发者ID:mathics,项目名称:Mathics,代码行数:51,代码来源:calculus.py


示例8: apply

    def apply(self, z, evaluation):
        '%(name)s[z__]'

        args = z.numerify(evaluation).get_sequence()
        mpmath_function = self.get_mpmath_function(args)
        result = None

        # if no arguments are inexact attempt to use sympy
        if all(not x.is_inexact() for x in args):
            result = Expression(self.get_name(), *args).to_sympy()
            result = self.prepare_mathics(result)
            result = from_sympy(result)
            # evaluate leaves to convert e.g. Plus[2, I] -> Complex[2, 1]
            return result.evaluate_leaves(evaluation)
        elif mpmath_function is None:
            return

        if not all(isinstance(arg, Number) for arg in args):
            return

        if any(arg.is_machine_precision() for arg in args):
            # if any argument has machine precision then the entire calculation
            # is done with machine precision.
            float_args = [arg.round().get_float_value(permit_complex=True) for arg in args]
            if None in float_args:
                return

            result = self.call_mpmath(mpmath_function, float_args)
            if isinstance(result, (mpmath.mpc, mpmath.mpf)):
                if mpmath.isinf(result) and isinstance(result, mpmath.mpc):
                    result = Symbol('ComplexInfinity')
                elif mpmath.isinf(result) and result > 0:
                    result = Expression('DirectedInfinity', Integer(1))
                elif mpmath.isinf(result) and result < 0:
                    result = Expression('DirectedInfinity', Integer(-1))
                elif mpmath.isnan(result):
                    result = Symbol('Indeterminate')
                else:
                    result = Number.from_mpmath(result)
        else:
            prec = min_prec(*args)
            d = dps(prec)
            args = [Expression('N', arg, Integer(d)).evaluate(evaluation) for arg in args]
            with mpmath.workprec(prec):
                mpmath_args = [x.to_mpmath() for x in args]
                if None in mpmath_args:
                    return
                result = self.call_mpmath(mpmath_function, mpmath_args)
                if isinstance(result, (mpmath.mpc, mpmath.mpf)):
                    result = Number.from_mpmath(result, d)
        return result
开发者ID:poke1024,项目名称:Mathics,代码行数:51,代码来源:arithmetic.py


示例9: apply_makeboxes

    def apply_makeboxes(self, expr, n, f, evaluation):
        """MakeBoxes[BaseForm[expr_, n_],
            f:StandardForm|TraditionalForm|OutputForm]"""

        base = n.get_int_value()

        if base <= 0:
            evaluation.message("BaseForm", "intpm", expr, n)
            return

        if not (isinstance(expr, Integer) or isinstance(expr, Real)):
            return Expression("MakeBoxes", expr, f)

        p = dps(expr.get_precision()) if isinstance(expr, Real) else 0
        val = convert_base(expr.get_real_value(), base, p)

        if f.get_name() == "OutputForm":
            return from_python("%s_%d" % (val, base))
        else:
            return Expression("SubscriptBox", from_python(val), from_python(base))
开发者ID:NitikaAgarwal,项目名称:Mathics,代码行数:20,代码来源:numeric.py


示例10: apply_N

 def apply_N(self, precision, evaluation):
     'N[E, precision_]'
     precision = get_precision(precision, evaluation)
     if precision is not None:
         return Real(sympy.E.n(dps(precision)), p=precision)
开发者ID:ashtonbaker,项目名称:Mathics,代码行数:5,代码来源:exptrig.py


示例11: apply

    def apply(self, items, evaluation):
        "Plus[items___]"

        items = items.numerify(evaluation).get_sequence()
        leaves = []
        last_item = last_count = None

        prec = min_prec(*items)
        is_real = all([not isinstance(i, Complex) for i in items])

        if prec is None:
            number = (sympy.Integer(0), sympy.Integer(0))
        else:
            number = (sympy.Float("0.0", dps(prec)), sympy.Float("0.0", dps(prec)))

        def append_last():
            if last_item is not None:
                if last_count == 1:
                    leaves.append(last_item)
                else:
                    if last_item.has_form("Times", None):
                        last_item.leaves.insert(0, Number.from_mp(last_count))
                        leaves.append(last_item)
                    else:
                        leaves.append(Expression("Times", Number.from_mp(last_count), last_item))

        for item in items:
            if isinstance(item, Number):
                # TODO: Optimise this for the case of adding many real numbers
                if isinstance(item, Complex):
                    sym_real, sym_imag = item.real.to_sympy(), item.imag.to_sympy()
                else:
                    sym_real, sym_imag = item.to_sympy(), sympy.Integer(0)

                if prec is not None:
                    sym_real = sym_real.n(dps(prec))
                    sym_imag = sym_imag.n(dps(prec))

                number = (number[0] + sym_real, number[1] + sym_imag)
            else:
                count = rest = None
                if item.has_form("Times", None):
                    for leaf in item.leaves:
                        if isinstance(leaf, Number):
                            count = leaf.to_sympy()
                            rest = item.leaves[:]
                            rest.remove(leaf)
                            if len(rest) == 1:
                                rest = rest[0]
                            else:
                                rest.sort()
                                rest = Expression("Times", *rest)
                            break
                if count is None:
                    count = sympy.Integer(1)
                    rest = item
                if last_item is not None and last_item == rest:
                    last_count = add(last_count, count)
                else:
                    append_last()
                    last_item = rest
                    last_count = count
        append_last()
        if prec is not None or number != (0, 0):
            if number[1].is_zero and is_real:
                leaves.insert(0, Number.from_mp(number[0], prec))
            elif number[1].is_zero and number[1].is_Integer and prec is None:
                leaves.insert(0, Number.from_mp(number[0], prec))
            else:
                leaves.insert(0, Complex(number[0], number[1], prec))
        if not leaves:
            return Integer(0)
        elif len(leaves) == 1:
            return leaves[0]
        else:
            leaves.sort()
            return Expression("Plus", *leaves)
开发者ID:sitelmi,项目名称:Mathics,代码行数:77,代码来源:arithmetic.py


示例12: dps

Support for numeric evaluation with arbitrary precision is just a proof-of-concept.
Precision is not "guarded" through the evaluation process. Only integer precision is supported.
However, things like 'N[Pi, 100]' should work as expected.
"""

from gmpy import mpz, mpf
import mpmath
from mpmath import mpi

from mathics.builtin.base import Builtin, Predefined
from mathics.core.numbers import dps, mpmath2gmpy
from mathics.core import numbers
from mathics.core.expression import Integer, Rational, Real, Complex, Atom, Expression, Number, Symbol

machine_precision = dps(mpf(64))


def get_precision(prec, evaluation):
    if prec.get_name() == "MachinePrecision":
        return numbers.prec(machine_precision)
    elif isinstance(prec, (Integer, Rational, Real)):
        return numbers.prec(prec.value)
    else:
        evaluation.message("N", "precbd", prec)
        return None


class N(Builtin):
    """
    <dl>
开发者ID:rnestler,项目名称:Mathics,代码行数:30,代码来源:numeric.py


示例13: apply_N

 def apply_N(self, precision, evaluation):
     "N[Pi, precision_]"
     precision = get_precision(precision, evaluation)
     if precision is not None:
         return Real(sympy.pi.n(dps(precision)), p=precision)
开发者ID:vpereira,项目名称:Mathics,代码行数:5,代码来源:exptrig.py


示例14: apply_N

    def apply_N(self, prec, evaluation):
        'N[MachinePrecision, prec_]'

        prec = get_precision(prec, evaluation)
        if prec is not None:
            return Real(dps(machine_precision), prec)
开发者ID:kirpit,项目名称:Mathics,代码行数:6,代码来源:numeric.py


示例15: apply_real

    def apply_real(self, x, evaluation):
        'Precision[x_Real]'

        return Real(dps(x.get_precision()))
开发者ID:kirpit,项目名称:Mathics,代码行数:4,代码来源:numeric.py


示例16: t_number

    def t_number(self, t):
        r'''
        ( (?# Two possible forms depending on whether base is specified)
            (\d+\^\^([a-zA-Z0-9]+\.?[a-zA-Z0-9]*|[a-zA-Z0-9]*\.?[a-zA-Z0-9]+))
            | (\d+\.?\d*|\d*\.?\d+)
        )
        (``?(\+|-)?(\d+\.?\d*|\d*\.?\d+)|`)?        (?# Precision / Accuracy)
        (\*\^(\+|-)?\d+)?                           (?# Exponent)
        '''
        s = t.value

        # Look for base
        s = s.split('^^')
        if len(s) == 1:
            base, s = 10, s[0]
        else:
            assert len(s) == 2
            base, s = int(s[0]), s[1]
            assert 2 <= base <= 36

        # Look for mantissa
        s = s.split('*^')
        if len(s) == 1:
            n, s = 0, s[0]
        else:
            # TODO: modify regex and provide error message if n not an int
            n, s = int(s[1]), s[0]

        # Look at precision ` suffix to get precision/accuracy
        prec, acc = None, None
        s = s.split('`', 1)
        if len(s) == 1:
            suffix, s = None, s[0]
        else:
            suffix, s = s[1], s[0]

            if suffix == '':
                prec = machine_precision
            elif suffix.startswith('`'):
                acc = float(suffix[1:])
            else:
                if re.match('0+$', s) is not None:
                    t.value = Integer(0)
                    return t
                prec = float(suffix)

        # Look for decimal point
        if s.count('.') == 0:
            if suffix is None:
                if n < 0:
                    t.value = Rational(int(s, base), base ** abs(n))
                else:
                    t.value = Integer(int(s, base) * (base ** n))
                return t
            else:
                s = s + '.'

        if base == 10:
            if n != 0:
                s = s + 'E' + str(n)    # sympy handles this

            if acc is not None:
                if float(s) == 0:
                    prec = 0.
                else:
                    prec = acc + log10(float(s)) + n

            # XXX
            if prec is not None:
                prec = dps(prec)
            t.value = Real(s, prec)
            # t.value = Real(s, prec, acc)
        else:
            # Convert the base
            assert isinstance(base, int) and 2 <= base <= 36

            # Put into standard form mantissa * base ^ n
            s = s.split('.')
            if len(s) == 1:
                man = s[0]
            else:
                n -= len(s[1])
                man = s[0] + s[1]

            man = int(man, base)

            if n >= 0:
                result = Integer(man * base ** n)
            else:
                result = Rational(man, base ** -n)

            if acc is None and prec is None:
                acc = len(s[1])
                acc10 = acc * log10(base)
                prec10 = acc10 + log10(result.to_python())
                if prec10 < 18:
                    prec10 = None
            elif acc is not None:
                acc10 = acc * log10(base)
                prec10 = acc10 + log10(result.to_python())
#.........这里部分代码省略.........
开发者ID:EgoIncarnate,项目名称:Mathics,代码行数:101,代码来源:parser.py


示例17: dps

Support for numeric evaluation with arbitrary precision is just a proof-of-concept.
Precision is not "guarded" through the evaluation process. Only integer precision is supported.
However, things like 'N[Pi, 100]' should work as expected.
"""

from gmpy import mpz, mpf
import mpmath
from mpmath import mpi

from mathics.builtin.base import Builtin, Predefined
from mathics.core.numbers import dps, mpmath2gmpy
from mathics.core import numbers
from mathics.core.expression import Integer, Rational, Real, Complex, Atom, Expression, Number, Symbol

machine_precision = dps(mpf(53))

def get_precision(prec, evaluation):
    if prec.get_name() == 'MachinePrecision':
        return numbers.prec(machine_precision)
    elif isinstance(prec, (Integer, Rational, Real)):
        return numbers.prec(prec.value)
    else:
        evaluation.message('N', 'precbd', prec)
        return None

class N(Builtin):
    """
    <dl>
    <dt>'N[$expr$, $prec$]'
        <dd>evaluates $expr$ numerically with a precision of $prec$ digits.
开发者ID:cjiang,项目名称:Mathics,代码行数:30,代码来源:numeric.py



注:本文中的mathics.core.numbers.dps函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python parser.parse函数代码示例发布时间:2022-05-27
下一篇:
Python expression.Number类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap