Skip to content

Slow implementation of round to significant digits function #1025

Description

@ValentinGebhart

Describe the problem
The functions util.value_representation.sig_dig and util.value_representation.sig_dig_list seem to be a bit slow (they convert the float input to a string and back).

def sig_dig(x, n_sig_dig=16):
    num_of_digits = len(str(x).replace(".", ""))
    if n_sig_dig >= num_of_digits:
        return x
    n = math.floor(math.log10(abs(x)) + 1 - n_sig_dig)
    result = decimal.Decimal(str(np.round(x * 10 ** (-n)))) * decimal.Decimal(
        str(10**n)
    )
    return float(result)

E.g., this function seemed to be more than 100 times faster. It created some floating point issues though and is thus not implemented.

def round_to_sig_digits(x, n_sig_dig):
    x = np.asarray(x, dtype=np.float64)  # Ensure consistent precision
    x_positive = np.where(np.isfinite(x) & (x != 0), np.abs(x), 10 ** (n_sig_dig - 1))
    mags = 10 ** (n_sig_dig - 1 - np.floor(np.log10(x_positive)))
    return np.around(x * mags) / mags

The function does not seem to be used much so this might not be urgent.

Activity

  1. peanutfun commented on Oct 15, 2025

    @peanutfun
    Member

    @ValentinGebhart Was this solved by #1012?

  2. ValentinGebhart commented on Oct 15, 2025

    @ValentinGebhart
    CollaboratorAuthor

    No, we created this issue to document a problem with an existing method. The suggested solution also has its downs, which is why we did not change the method, and we currently do not plan to do so.

    If such issues should rather be documented somewhere else, happy to move this issue and close it here.

  3. peanutfun commented on Oct 15, 2025

    @peanutfun
    Member

    I'll convert this to a Discussion, then.

  4. locked and limited conversation to collaborators on Oct 15, 2025
  5. converted this issue into a discussion #1099 on Oct 15, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions