MCPcopy Index your code
hub / github.com/RustPython/RustPython / from_float

Method from_float

Lib/_pydecimal.py:624–666  ·  view source on GitHub ↗

Converts a float to a decimal number, exactly. Note that Decimal.from_float(0.1) is not the same as Decimal('0.1'). Since 0.1 is not exactly representable in binary floating point, the value is stored as the nearest representable value which is 0x1.999999999999ap-4.

(cls, f)

Source from the content-addressed store, hash-verified

622
623 @classmethod
624 def from_float(cls, f):
625 """Converts a float to a decimal number, exactly.
626
627 Note that Decimal.from_float(0.1) is not the same as Decimal('0.1').
628 Since 0.1 is not exactly representable in binary floating point, the
629 value is stored as the nearest representable value which is
630 0x1.999999999999ap-4. The exact equivalent of the value in decimal
631 is 0.1000000000000000055511151231257827021181583404541015625.
632
633 >>> Decimal.from_float(0.1)
634 Decimal('0.1000000000000000055511151231257827021181583404541015625')
635 >>> Decimal.from_float(float('nan'))
636 Decimal('NaN')
637 >>> Decimal.from_float(float('inf'))
638 Decimal('Infinity')
639 >>> Decimal.from_float(-float('inf'))
640 Decimal('-Infinity')
641 >>> Decimal.from_float(-0.0)
642 Decimal('-0')
643
644 """
645 if isinstance(f, int): # handle integer inputs
646 sign = 0 if f >= 0 else 1
647 k = 0
648 coeff = str(abs(f))
649 elif isinstance(f, float):
650 if _math.isinf(f) or _math.isnan(f):
651 return cls(repr(f))
652 if _math.copysign(1.0, f) == 1.0:
653 sign = 0
654 else:
655 sign = 1
656 n, d = abs(f).as_integer_ratio()
657 k = d.bit_length() - 1
658 coeff = str(n*5**k)
659 else:
660 raise TypeError("argument must be int or float.")
661
662 result = _dec_from_triple(sign, coeff, -k)
663 if cls is Decimal:
664 return result
665 else:
666 return cls(result)
667
668 def _isnan(self):
669 """Returns whether the number is not actually one.

Callers 4

__new__Method · 0.45
_convert_otherFunction · 0.45
_convert_for_comparisonFunction · 0.45

Calls 8

isinstanceFunction · 0.85
strFunction · 0.85
reprFunction · 0.85
_dec_from_tripleFunction · 0.85
absFunction · 0.70
clsClass · 0.50
as_integer_ratioMethod · 0.45
bit_lengthMethod · 0.45

Tested by

no test coverage detected