Skip to content

Instantly share code, notes, and snippets.

@jpcbertoldo
Created June 7, 2023 15:23
Show Gist options
  • Save jpcbertoldo/92370a121ac4f77775fb9c9362ea173e to your computer and use it in GitHub Desktop.
Save jpcbertoldo/92370a121ac4f77775fb9c9362ea173e to your computer and use it in GitHub Desktop.
A function to round up an array of values based on the number of significant digits (useful for sequences spanning over many scales)
"""
Source of the idea: https://stackoverflow.com/a/58491045/9582881
"""
import numpy as np
def round_significant_digits(x, dtype=np.float64, precision=4):
string = np.format_float_positional(x, unique=False, fractional=False, trim='k', precision=precision)
return dtype(string)
round_significant_digits_vectorized = np.vectorize(round_significant_digits, )
x = np.array([1234567890] * 10) / np.logspace(0, 9, 10)
# [1.23456789e+09 1.23456789e+08 1.23456789e+07 1.23456789e+06
# 1.23456789e+05 1.23456789e+04 1.23456789e+03 1.23456789e+02
# 1.23456789e+01 1.23456789e+00]
y = round_significant_digits_vectorized(x, precision=3)
# [1.23e+09 1.23e+08 1.23e+07 1.23e+06 1.23e+05 1.23e+04 1.23e+03 1.23e+02
# 1.23e+01 1.23e+00]
print(x)
print(y)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment