我们从Python开源项目中,提取了以下12个代码示例,用于说明如何使用sympy.Number()。
def __init__(self, name, param, arg, circuit=None): """Create a new instruction. name = instruction name string param = list of real parameters arg = list of pairs (Register, index) circuit = QuantumCircuit or CompositeGate containing this instruction """ for i in arg: if not isinstance(i[0], Register): raise QISKitError("argument not (Register, int) tuple") self.name = name self.param = [] for p in param: if not isinstance(p, Basic): # if item in param not symbolic, make it symbolic self.param.append(Number(p)) else: self.param.append(p) self.arg = arg self.control = None # tuple (ClassicalRegister, int) for "if" self.circuit = circuit
def as_symbol(expr): """ Extract the "main" symbol from a SymPy object. """ try: return Number(expr) except (TypeError, ValueError): pass if isinstance(expr, str): return Symbol(expr) elif isinstance(expr, Dimension): return Symbol(expr.name) elif expr.is_Symbol: return expr elif isinstance(expr, Indexed): return expr.base.label elif isinstance(expr, Function): return Symbol(expr.__class__.__name__) else: raise TypeError("Cannot extract symbol from type %s" % type(expr))
def manual_diff(f, symbol): """Derivative of f in form expected by find_substitutions SymPy's derivatives for some trig functions (like cot) aren't in a form that works well with finding substitutions; this replaces the derivatives for those particular forms with something that works better. """ if f.args: arg = f.args[0] if isinstance(f, sympy.tan): return arg.diff(symbol) * sympy.sec(arg)**2 elif isinstance(f, sympy.cot): return -arg.diff(symbol) * sympy.csc(arg)**2 elif isinstance(f, sympy.sec): return arg.diff(symbol) * sympy.sec(arg) * sympy.tan(arg) elif isinstance(f, sympy.csc): return -arg.diff(symbol) * sympy.csc(arg) * sympy.cot(arg) elif isinstance(f, sympy.Add): return sum([manual_diff(arg, symbol) for arg in f.args]) elif isinstance(f, sympy.Mul): if len(f.args) == 2 and isinstance(f.args[0], sympy.Number): return f.args[0] * manual_diff(f.args[1], symbol) return f.diff(symbol) # Method based on that on SIN, described in "Symbolic Integration: The # Stormy Decade"
def t_REAL(self, t): r'(([0-9]+|([0-9]+)?\.[0-9]+|[0-9]+\.)[eE][+-]?[0-9]+)|(([0-9]+)?\.[0-9]+|[0-9]+\.)' t.value = Number(t.value) # tad nasty, see mkfloat.py to see how this is derived from python spec return t
def p_unary_1(self, program): """ unary : REAL """ program[0] = node.Real(sympy.Number(program[1]))
def _print_Number(self, e): """Print a Number object. :param e: The expression. :rtype : bce.dom.mathml.all.Base :return: The printed MathML object. """ assert isinstance(e, _sympy.Number) return _mathml.NumberComponent(str(e))
def test_issue_9398(): from sympy import Number, cancel assert cancel(1e-14) != 0 assert cancel(1e-14*I) != 0 assert simplify(1e-14) != 0 assert simplify(1e-14*I) != 0 assert (I*Number(1.)*Number(10)**Number(-14)).simplify() != 0 assert cancel(1e-20) != 0 assert cancel(1e-20*I) != 0 assert simplify(1e-20) != 0 assert simplify(1e-20*I) != 0 assert cancel(1e-100) != 0 assert cancel(1e-100*I) != 0 assert simplify(1e-100) != 0 assert simplify(1e-100*I) != 0 f = Float("1e-1000") assert cancel(f) != 0 assert cancel(f*I) != 0 assert simplify(f) != 0 assert simplify(f*I) != 0
def _to_mpmath(self, prec, allow_ints=True): # mpmath functions accept ints as input errmsg = "cannot convert to mpmath number" if allow_ints and self.is_Integer: return self.p if hasattr(self, '_as_mpf_val'): return make_mpf(self._as_mpf_val(prec)) try: re, im, _, _ = evalf(self, prec, {}) if im: if not re: re = fzero return make_mpc((re, im)) elif re: return make_mpf(re) else: return make_mpf(fzero) except NotImplementedError: v = self._eval_evalf(prec) if v is None: raise ValueError(errmsg) if v.is_Float: return make_mpf(v._mpf_) # Number + Number*I is also fine re, im = v.as_real_imag() if allow_ints and re.is_Integer: re = from_int(re.p) elif re.is_Float: re = re._mpf_ else: raise ValueError(errmsg) if allow_ints and im.is_Integer: im = from_int(im.p) elif im.is_Float: im = im._mpf_ else: raise ValueError(errmsg) return make_mpc((re, im))
def test_abbrev(): u = Quantity("u", length, 1) assert u.name == Symbol("u") assert u.abbrev == Symbol("u") u = Quantity("u", length, 2, "om") assert u.name == Symbol("u") assert u.abbrev == Symbol("om") assert u.scale_factor == 2 assert isinstance(u.scale_factor, Number) u = Quantity("u", length, 3*kilo, "ikm") assert u.abbrev == Symbol("ikm") assert u.scale_factor == 3000
def merge_explicit(matmul): """ Merge explicit MatrixBase arguments >>> from sympy import MatrixSymbol, eye, Matrix, MatMul, pprint >>> from sympy.matrices.expressions.matmul import merge_explicit >>> A = MatrixSymbol('A', 2, 2) >>> B = Matrix([[1, 1], [1, 1]]) >>> C = Matrix([[1, 2], [3, 4]]) >>> X = MatMul(A, B, C) >>> pprint(X) [1 1] [1 2] A*[ ]*[ ] [1 1] [3 4] >>> pprint(merge_explicit(X)) [4 6] A*[ ] [4 6] >>> X = MatMul(B, A, C) >>> pprint(X) [1 1] [1 2] [ ]*A*[ ] [1 1] [3 4] >>> pprint(merge_explicit(X)) [1 1] [1 2] [ ]*A*[ ] [1 1] [3 4] """ if not any(isinstance(arg, MatrixBase) for arg in matmul.args): return matmul newargs = [] last = matmul.args[0] for arg in matmul.args[1:]: if isinstance(arg, (MatrixBase, Number)) and isinstance(last, (MatrixBase, Number)): last = last * arg else: newargs.append(last) last = arg newargs.append(last) return MatMul(*newargs)
def is_scalar_nonsparse_matrix(circuit, nqubits, identity_only): """Checks if a given circuit, in matrix form, is equivalent to a scalar value. Parameters ========== circuit : Gate tuple Sequence of quantum gates representing a quantum circuit nqubits : int Number of qubits in the circuit identity_only : bool Check for only identity matrices Note: Used in situations when is_scalar_sparse_matrix has bugs """ matrix = represent(Mul(*circuit), nqubits=nqubits) # In some cases, represent returns a 1D scalar value in place # of a multi-dimensional scalar matrix if (isinstance(matrix, Number)): return matrix == 1 if identity_only else True # If represent returns a matrix, check if the matrix is diagonal # and if every item along the diagonal is the same else: # Added up the diagonal elements matrix_trace = matrix.trace() # Divide the trace by the first element in the matrix # if matrix is not required to be the identity matrix adjusted_matrix_trace = (matrix_trace/matrix[0] if not identity_only else matrix_trace) is_identity = matrix[0] == 1.0 if identity_only else True has_correct_trace = adjusted_matrix_trace == pow(2, nqubits) # The matrix is scalar if it's diagonal and the adjusted trace # value is equal to 2^nqubits return bool( matrix.is_diagonal() and has_correct_trace and is_identity)