Avatar ·

What is the difference between different ways to extract a root in Python?

📁 python, пример

In Python, you can extract a root in three ways: x ** 0.5, pow(x, 0.5), math.sqrt(x). And for integers with an integer result, there is also math.isqrt(x). What is the difference between them?

P.S. For example, when checking if n is prime, you need to loop up to the square root of n. Is this correct?

for i in range(2, int(n ** 0.5) + 1):    ...

The primary concern is correctness (accuracy of calculations). Performance is secondary.

Avatar ·

In the code:

  • try_repeat – a decorator that repeats a function call if it raises an exception.
  • exception_func – a function that throws an exception with a 50% probability

Example:

def try_repeat(func):    def wrapper(*args, **kwargs):        count = 10        while count:            try:                retu func(*args, **kwargs)            except Exception as e:                print(
                            

Log in to leave an answer

Интересные статьи