Round off a list of decimal numbers to 4 significant figures without loops.

Ayush Kumar
Ayush Kumar Member, Moderator, Employee Posts: 472
100 Answers 250 Likes 100 Comments Second Anniversary
✭✭✭✭

Round off a list of decimal numbers to 4 significant figures without loops.

Tagged:

Comments

  • Ayush Kumar
    Ayush Kumar Member, Moderator, Employee Posts: 472
    100 Answers 250 Likes 100 Comments Second Anniversary
    ✭✭✭✭
    edited January 14

    The following code generates a random list of a million numbers with 8 decimal points and rounds off to 4 significant digits.

    import time
    import random
    from math import log10, ceil
    
    
    def generate_numbers(count, decimal_places):
      """
      Generates a list of random numbers with specified decimal places.
      """
      return [round(random.uniform(0, 1), decimal_places) for _ in range(count)]
    
    
    def round_to_4_sigfigs(numbers):
        """
        Rounds a list of numbers to 4 significant figures.
        """
        def sigfig_round(x):
            if x == 0:
                return 0.0
            decimals = int(ceil(-log10(abs(x)))) + 3
            return round(x, decimals)
        return list(map(sigfig_round, numbers))
    
    
    million_numbers = generate_numbers(1000000, 8)
    
    t1 = time.time()
    rounded_numbers = round_to_4_sigfigs(million_numbers)
    t2 = time.time()
    
    print(t2 - t1)