steph1111 / PRECISE

Precision Rules Enforced Calculations In Scientific Environments
Other
0 stars 0 forks source link

sig_float: Consider rewriting the sig_figs() function to be more efficient and shorter #33

Closed steph1111 closed 1 year ago

steph1111 commented 1 year ago

Rambling so I remember the idea later: What if I found the number of trailing zeros, then converted to a float, found the digits of said float, + the number of trailing zeros if decimal then created a new string representation using the numeric and trailing zeros. Might result in cleaner code because leading zeros will be removed automatically and the negative and decimal will be accounted for, this makes sense if python has a methord for counting the number of digits in an object.

steph1111 commented 1 year ago
  def sig_figs(self) -> int:
    """
    Returns the number of sig figs of a sig_float object
    """
    negative = True if self._str[0] == "-" else False

    # Remove leading zeros and negative
    self._str = self._str.lstrip("-00̅")

    # Count the initial sig figs from the front
    sig_figs_count = len(self._str.lstrip(".0"))

    # Count the sig figs from the back
    if self._str.find(".") != -1 and self._str[0] != ".":
      sig_figs_count -= 1
    elif self._str.find(".") == -1 and self._str[0] != ".":
      sig_figs_count -= len(self._str) - len(self._str.rstrip("00̅"))

    # Re build the string representation
    self._str = "-0" + self._str if negative and self._str[0] == "." else "0" + self._str if self._str[
        0] == "." else "-" + self._str if negative else self._str