Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

In my field it's very common to square some numbers, operate them together, and take the square root of the result. This is done in the Pythagorean theorem, and the RMS calculation, for example.

In numpy, I have done the following:

result = numpy.sqrt(numpy.sum(numpy.pow(some_vector, 2)))

And in pure python something like this would be expected:

result = math.sqrt(math.pow(A, 2) + math.pow(B,2)) 

# example with two dimensions.

However, I have been using this pure python form, since I find it much more compact, import-independent, and seemingly equivalent:

result = (A**2 + B**2)**0.5 # two dimensions 

result = (A**2 + B**2 + C**2 + D**2)**0.5

I have heard some people argue that the ** operator is sort of a hack and that squaring a number by exponentiating it by 0.5 is not so readable. But what I'd like to ask is if:

"Is there any COMPUTATIONAL reason to prefer the former two alternatives over the third one(s)?"

Thanks for reading!

1 Answer

0 votes
by (106k points)

Even in base Python you can do the computation in generic form

result = sum(x**2 for x in some_vector) ** 0.5

x ** 2 is surely not a hack and the computation performed is the same (I checked with CPython source code). I actually find it more readable (and readability counts).

To know more about this you can have a look at the following video tutorial:-

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...