0

I was recently working with Python and wanted to use another way of finding square roots. For example I wanted to find square root of n with Newton-Raphson approximation. I need to overload the overload the ** (only when you raise a number to 0.5),o perator as well as math.sqrt(), because I have several older projects that could be sped up by doing so and replacing all math.sqrt() and **(0.5) with another function isn't ideal.

Could this be done in Python?

Is it possible to overload either ** or math.sqrt?

Any helpful links are also much appreciated.

def Square_root(n):
    r = n/2
    while(abs(r-(n/r)) > t):
        r = 0.5 * (r + (n/r))
    return r

print(2**(0.5)) ## changes to print(Square_root(2))
print(math.sqrt(2)) ## that also becomes print(Square_root(2))
2
  • 1
    You can overload ** (or any other operator) only for the members of your custom classes. I do not believe you can redefine math.sqrt(). Commented Apr 16, 2017 at 20:29
  • Yes, that's possible, but you really shouldn't do it. Anyone else looking through the source code of the program will expect ** and math.sqrt() to work like they do normally, so the different behavior will probably cause a lot of confusion... Commented Apr 16, 2017 at 20:33

2 Answers 2

1

In short: you can't change the behavior of __pow__ for built-in types.

Long answer: you can subclass the float, but it will require additional coding and refactoring of the input values of the program, to the new float class with overwritten operators and functions.

And you can overwrite the math.sqrt, but this is not recommended:

import math
math.sqrt = lambda x, y: print(x, y)
math.sqrt(3, 2)
# 3 2

This will require the custom function to have the same signature.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. The code snippet was what I was looking for. As for pow I guess I will have to leave that as is.
1

If you really want to overload languages int and float objects - you can use variants of magic functions. In order to be consistent, you'll have to write a lot of code.

A lot of work. Python is for lazy people - if you like to write a lot, stick to Java or C++ :)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.