Python sympy.Float() Examples
The following are 19
code examples of sympy.Float().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
sympy
, or try the search function
.
Example #1
Source File: expressions.py From qupulse with MIT License | 6 votes |
def _parse_evaluate_numeric_result(self, result: Union[Number, numpy.ndarray], call_arguments: Any) -> Union[Number, numpy.ndarray]: allowed_types = (float, numpy.number, int, complex, bool, numpy.bool_, TimeType) if isinstance(result, tuple): result = numpy.array(result) if isinstance(result, numpy.ndarray): if issubclass(result.dtype.type, allowed_types): return result else: obj_types = set(map(type, result.flat)) if obj_types == {sympy.Float} or obj_types == {sympy.Float, sympy.Integer}: return result.astype(float) elif obj_types == {sympy.Integer}: return result.astype(numpy.int64) else: raise NonNumericEvaluation(self, result, call_arguments) elif isinstance(result, allowed_types): return result elif isinstance(result, sympy.Float): return float(result) elif isinstance(result, sympy.Integer): return int(result) else: raise NonNumericEvaluation(self, result, call_arguments)
Example #2
Source File: basic.py From devito with MIT License | 6 votes |
def indexify(self, indices=None, lshift=False, subs=None): """Create a types.Indexed from the current object.""" if indices is not None: return Indexed(self.indexed, *indices) # Substitution for each index (spacing only used in own dimension) subs = subs or {} subs = [{**{d.spacing: 1, -d.spacing: -1}, **subs} for d in self.dimensions] # Add halo shift shift = self._size_nodomain.left if lshift else tuple([0]*len(self.dimensions)) # Indices after substitutions indices = [sympy.sympify((a - o + f).xreplace(s)) for a, o, f, s in zip(self.args, self.origin, shift, subs)] indices = [i.xreplace({k: sympy.Integer(k) for k in i.atoms(sympy.Float)}) for i in indices] return self.indexed[indices]
Example #3
Source File: _expr.py From chempy with BSD 2-Clause "Simplified" License | 6 votes |
def _sympy_format(self, method, variables, backend, default, **kwargs): variables = variables or {} if backend in (None, math): backend = sympy variables = defaultkeydict( None if default is None else (lambda k: backend.Symbol(default(k))), {k: v if isinstance(v, Expr) else (backend.Symbol(v) if isinstance(v, str) else backend.Float(v)) for k, v in variables.items()}) expr = self(variables, backend=backend, **kwargs).simplify() if method == 'latex': return backend.latex(expr) elif method == 'str': return str(expr) elif method == 'unicode': return backend.pretty(expr, use_unicode=True) elif method == 'mathml': from sympy.printing.mathml import mathml return mathml(expr) else: raise NotImplementedError("Unknown method: %s" % method)
Example #4
Source File: json_serialization_test.py From Cirq with Apache License 2.0 | 6 votes |
def test_sympy(): # Raw values. assert_json_roundtrip_works(sympy.Symbol('theta')) assert_json_roundtrip_works(sympy.Integer(5)) assert_json_roundtrip_works(sympy.Rational(2, 3)) assert_json_roundtrip_works(sympy.Float(1.1)) # Basic operations. s = sympy.Symbol('s') t = sympy.Symbol('t') assert_json_roundtrip_works(t + s) assert_json_roundtrip_works(t * s) assert_json_roundtrip_works(t / s) assert_json_roundtrip_works(t - s) assert_json_roundtrip_works(t**s) # Linear combinations. assert_json_roundtrip_works(t * 2) assert_json_roundtrip_works(4 * t + 3 * s + 2)
Example #5
Source File: duration.py From Cirq with Apache License 2.0 | 5 votes |
def _decompose_into_amount_unit_suffix(self) -> Tuple[int, str, str]: if (isinstance(self._picos, sympy.Mul) and len(self._picos.args) == 2 and isinstance(self._picos.args[0], (sympy.Integer, sympy.Float))): scale = self._picos.args[0] rest = self._picos.args[1] else: scale = self._picos rest = 1 if scale % 1000_000_000 == 0: amount = scale / 1000_000_000 unit = 'millis' suffix = 'ms'
Example #6
Source File: test_symbolics.py From devito with MIT License | 5 votes |
def test_solve(so): """ Test that our solve produces the correct output and faster than sympy's default behavior for an affine equation (i.e. PDE time steppers). """ grid = Grid((10, 10, 10)) u = TimeFunction(name="u", grid=grid, time_order=2, space_order=so) v = Function(name="v", grid=grid, space_order=so) eq = u.dt2 - div(v * grad(u)) # Standard sympy solve t0 = time.time() sol1 = sympy.solve(eq.evaluate, u.forward, rational=False, simplify=False)[0] t1 = time.time() - t0 # Devito custom solve for linear equation in the target ax + b (most PDE tie steppers) t0 = time.time() sol2 = solve(eq.evaluate, u.forward) t12 = time.time() - t0 diff = sympy.simplify(sol1 - sol2) # Difference can end up with super small coeffs with different evaluation # so zero out everything very small assert diff.xreplace({k: 0 if abs(k) < 1e-10 else k for k in diff.atoms(sympy.Float)}) == 0 # Make sure faster (actually much more than 10 for very complex cases) assert t12 < t1/10
Example #7
Source File: test_symbolics.py From devito with MIT License | 5 votes |
def test_float_indices(): """ Test that indices only contain Integers. """ grid = Grid((10,)) x = grid.dimensions[0] x0 = x + 1.0 * x.spacing u = Function(name="u", grid=grid, space_order=2) indices = u.subs({x: x0}).indexify().indices[0] assert len(indices.atoms(sympy.Float)) == 0 assert indices == x + 1 indices = u.subs({x: 1.0}).indexify().indices[0] assert len(indices.atoms(sympy.Float)) == 0 assert indices == 1
Example #8
Source File: test_derivatives.py From devito with MIT License | 5 votes |
def test_fd_indices(self, so): """ Test that shifted derivative have Integer offset after indexification. """ grid = Grid((10,)) x = grid.dimensions[0] x0 = x + .5 * x.spacing u = Function(name="u", grid=grid, space_order=so) dx = indexify(u.dx(x0=x0).evaluate) for f in retrieve_indexed(dx): assert len(f.indices[0].atoms(Float)) == 0
Example #9
Source File: _expr.py From chempy with BSD 2-Clause "Simplified" License | 5 votes |
def _implicit_conversion(obj): if isinstance(obj, (int, float)): return Constant(obj) elif isinstance(obj, Expr): return obj elif isinstance(obj, str): return Symbol(unique_keys=(obj,)) if sympy is not None: if isinstance(obj, sympy.Mul): if len(obj.args) != 2: raise NotImplementedError("Did you use evaluate=False?") return _MulExpr([_implicit_conversion(obj.args[0]), _implicit_conversion(obj.args[1])]) elif isinstance(obj, sympy.Add): if len(obj.args) != 2: raise NotImplementedError("Did you use evaluate=False?") return _AddExpr([_implicit_conversion(obj.args[0]), _implicit_conversion(obj.args[1])]) elif isinstance(obj, sympy.Pow): return _PowExpr(_implicit_conversion(obj.base), _implicit_conversion(obj.exp)) elif isinstance(obj, sympy.Float): return Constant(float(obj)) elif isinstance(obj, sympy.Symbol): return Symbol(unique_keys=(obj.name,)) raise NotImplementedError( "Don't know how to convert %s (of type %s)" % (obj, type(obj)))
Example #10
Source File: quirk_gate.py From Cirq with Apache License 2.0 | 5 votes |
def _is_supported_formula(formula: sympy.Basic) -> bool: if isinstance(formula, (sympy.Symbol, sympy.Integer, sympy.Float, sympy.Rational, sympy.NumberSymbol)): return True if isinstance(formula, (sympy.Add, sympy.Mul)): return all(_is_supported_formula(f) for f in formula.args) return False
Example #11
Source File: sys_sympy.py From FreeCAD_assembly3 with GNU General Public License v3.0 | 5 votes |
def __init__(self,name,v,g): super(_Param,self).__init__(name,g) self.val = v self._sym = sp.Dummy(self._name,real=True) self._symobj = self._sym self._val = sp.Float(self.val)
Example #12
Source File: test_represent.py From sympsi with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_scalar_scipy_sparse(): if not np: skip("numpy not installed.") if not scipy: skip("scipy not installed.") assert represent(Integer(1), format='scipy.sparse') == 1 assert represent(Float(1.0), format='scipy.sparse') == 1.0 assert represent(1.0 + I, format='scipy.sparse') == 1.0 + 1.0j
Example #13
Source File: test_represent.py From sympsi with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_scalar_numpy(): if not np: skip("numpy not installed.") assert represent(Integer(1), format='numpy') == 1 assert represent(Float(1.0), format='numpy') == 1.0 assert represent(1.0 + I, format='numpy') == 1.0 + 1.0j
Example #14
Source File: test_represent.py From sympsi with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_scalar_sympy(): assert represent(Integer(1)) == Integer(1) assert represent(Float(1.0)) == Float(1.0) assert represent(1.0 + I) == 1.0 + I
Example #15
Source File: test_constants.py From sympsi with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_hbar(): assert hbar.is_commutative is True assert hbar.is_real is True assert hbar.is_positive is True assert hbar.is_negative is False assert hbar.is_irrational is True assert hbar.evalf() == Float(1.05457162e-34)
Example #16
Source File: test_sympy_conv.py From symengine.py with MIT License | 5 votes |
def test_mpc(): if have_mpc: a = ComplexMPC('1', '2', 100) b = sympy.Float(1, 29) + sympy.Float(2, 29) * sympy.I assert sympify(b) == a assert b == a._sympy_()
Example #17
Source File: test_sympy_conv.py From symengine.py with MIT License | 5 votes |
def test_mpfr(): if have_mpfr: a = RealMPFR('100', 100) b = sympy.Float('100', 29) assert sympify(b) == a assert b == a._sympy_()
Example #18
Source File: sys_sympy.py From FreeCAD_assembly3 with GNU General Public License v3.0 | 5 votes |
def getSymObj(self): return sp.Float(self.d)
Example #19
Source File: arg_func_langs.py From Cirq with Apache License 2.0 | 4 votes |
def _arg_to_proto(value: ARG_LIKE, *, arg_function_language: Optional[str], out: Optional[v2.program_pb2.Arg] = None ) -> v2.program_pb2.Arg: """Writes an argument value into an Arg proto. Args: value: The value to encode. arg_function_language: The language to use when encoding functions. If this is set to None, it will be set to the minimal language necessary to support the features that were actually used. out: The proto to write the result into. Defaults to a new instance. Returns: The proto that was written into as well as the `arg_function_language` that was used. """ if arg_function_language not in SUPPORTED_FUNCTIONS_FOR_LANGUAGE: raise ValueError(f'Unrecognized arg_function_language: ' f'{arg_function_language!r}') supported = SUPPORTED_FUNCTIONS_FOR_LANGUAGE[arg_function_language] msg = v2.program_pb2.Arg() if out is None else out def check_support(func_type: str) -> str: if func_type not in supported: lang = (repr(arg_function_language) if arg_function_language is not None else '[any]') raise ValueError(f'Function type {func_type!r} not supported by ' f'arg_function_language {lang}') return func_type if isinstance(value, (float, int, sympy.Integer, sympy.Float, sympy.Rational, sympy.NumberSymbol)): msg.arg_value.float_value = float(value) elif isinstance(value, str): msg.arg_value.string_value = value elif (isinstance(value, (list, tuple, np.ndarray)) and all(isinstance(x, (bool, np.bool_)) for x in value)): # Some protobuf / numpy combinations do not support np.bool_, so cast. msg.arg_value.bool_values.values.extend([bool(x) for x in value]) elif isinstance(value, sympy.Symbol): msg.symbol = str(value.free_symbols.pop()) elif isinstance(value, sympy.Add): msg.func.type = check_support('add') for arg in value.args: _arg_to_proto(arg, arg_function_language=arg_function_language, out=msg.func.args.add()) elif isinstance(value, sympy.Mul): msg.func.type = check_support('mul') for arg in value.args: _arg_to_proto(arg, arg_function_language=arg_function_language, out=msg.func.args.add()) else: raise ValueError(f'Unrecognized arg type: {type(value)}') return msg