473,799 Members | 3,080 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

"pow" (power) function

I have a couple of questions for the number crunchers out there:

Does "pow(x,2)" simply square x, or does it first compute logarithms
(as would be necessary if the exponent were not an integer)?

Does "x**0.5" use the same algorithm as "sqrt(x)", or does it use some
other (perhaps less efficient) algorithm based on logarithms?

Thanks,
Russ

Mar 15 '06
11 4454
"Russ" <uy*******@snea kemail.com> writes:
I just did a little time test (which I should have done *before* my
original post!), and 2.0**2 seems to be about twice as fast as
pow(2.0,2). That seems consistent with your claim above...>
I just did another little time test comparing 2.0**0.5 with sqrt(2.0).
Surprisingly, 2.0**0.5 seems to take around a third less time.


I think the explanation is likely here:

Python 2.3.4 (#1, Feb 2 2005, 12:11:53)
import dis
from math import sqrt
def f(x): return x**.5 ... dis.dis(f) 1 0 LOAD_FAST 0 (x)
3 LOAD_CONST 1 (0.5)
6 BINARY_POWER
7 RETURN_VALUE
8 LOAD_CONST 0 (None)
11 RETURN_VALUE

See, x**.5 does two immediate loads and an inline BINARY_POWER bytecode.
def g(x): return sqrt(x) ... dis.dis(g) 1 0 LOAD_GLOBAL 0 (sqrt)
3 LOAD_FAST 0 (x)
6 CALL_FUNCTION 1
9 RETURN_VALUE
10 LOAD_CONST 0 (None)
13 RETURN_VALUE

sqrt(x), on the other hand, does a lookup of 'sqrt' in the global
namespace, then does a Python function call, both of which likely
are almost as expensive as the C library pow(...) call.

If you do something like

def h(x, sqrt=sqrt):
return sqrt(x)

you replace the LOAD_GLOBAL with a LOAD_FAST and that might give a
slight speedup:
dis.dis(h)

2 0 LOAD_FAST 1 (sqrt)
3 LOAD_FAST 0 (x)
6 CALL_FUNCTION 1
9 RETURN_VALUE
10 LOAD_CONST 0 (None)
13 RETURN_VALUE
Mar 17 '06 #11
"Russ" <uy*******@snea kemail.com> writes:
Ben Cartwright wrote:
Russ wrote:

> Does "pow(x,2)" simply square x, or does it first compute logarithms
> (as would be necessary if the exponent were not an integer)?

The former, using binary exponentiation (quite fast), assuming x is an
int or long.

If x is a float, Python coerces the 2 to 2.0, and CPython's float_pow()
function is called. This function calls libm's pow(), which in turn
uses logarithms.


I just did a little time test (which I should have done *before* my
original post!), and 2.0**2 seems to be about twice as fast as
pow(2.0,2). That seems consistent with your claim above.

I'm a bit surprised that pow() would use logarithms even if the
exponent is an integer. I suppose that just checking for an integer
exponent could blow away the gain that would be achieved by avoiding
logarithms. On the other hand, I would think that using logarithms
could introduce a tiny error (e.g., pow(2.0,2) = 3.9999999996 <- made
up result) that wouldn't occur with multiplication.


It depends on the libm implementation of pow() whether logarithms are
used for integer exponents. I'm looking at glibc's (the libc used on
Linux) implementation for Intel processors, and it does optimize
integers. That routine is written in assembly language, btw.
> Does "x**0.5" use the same algorithm as "sqrt(x)", or does it use some
> other (perhaps less efficient) algorithm based on logarithms?


The latter, and that algorithm is libm's pow(). Except for a few
special cases that Python handles, all floating point exponentation is
left to libm. Checking to see if the exponent is 0.5 is not one of
those special cases.


I just did another little time test comparing 2.0**0.5 with sqrt(2.0).
Surprisingly, 2.0**0.5 seems to take around a third less time.

None of these differences are really significant unless one is doing
super-heavy-duty number crunching, of course, but I was just curious.
Thanks for the information.


And if you are, you'd likely be doing it on more than one number, in
which case you'd probably want to use numpy. We've optimized x**n so
that it does handle n=0.5 and integers specially; it makes more sense
to do this for an array of numbers where you can do the special
manipulation of the exponent, and then apply that to all the numbers
in the array at once.

--
|>|\/|<
/--------------------------------------------------------------------------\
|David M. Cooke
|cookedm(at)phy sics(dot)mcmast er(dot)ca
Mar 17 '06 #12

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
2214
by: Aaron Gallimore | last post by:
Hi, Pretty simple one I think...Is there a "power of" or squared function in C++. This is what i'm trying to achieve. (array-array)*2 this doesnt work with minus numbers so i need a square or power function. also.. Is there a "sum of" function. Ultimately i'm trying to do a euclidean
6
2723
by: M Welinder | last post by:
The title more or less says it all: in C99, is the value of INT_MIN % -1 well defined (when performed as signed integers) under the assumption of two-complement representation. Note, that this is not the usual negative-values-and-% question -- the problem here is that the corresponding signed division, INT_MIN / -1, overflows. Thus I don't see what use a%b = a-(a/b)*b can be here.
13
2099
by: Dave win | last post by:
howdy.... plz take a look at the following codes, and tell me the reason. 1 #define swap(a,b) a=a^b;b=b^a;a=a^b 2 3 int main(void){ 4 register int a=4; 5 register int b=5; 6 swap(a,b); 7
15
28827
by: Bjorn Jensen | last post by:
Hi! An beginner question: Pleas help me with this (-: Error (the arrow points on the s in sqrt) ===== tal.java:6: cannot find symbol symbol : method sqrt(int) location: class tal System.out.println(i + ": " + sqrt(4));
1
2895
by: Curten | last post by:
Hi, When I run a program I have made, i get this error message sometimes: "Application error:The instruction at '...' referenced memory at '...'. Memory could not be "read"..." Are there any common mistakes that cause this problem? Before i get the message above i get this in the command window: "pow: OVERFLOW error". I suppose these error messages are connected, but how? What causes pow: OVERFLOW error?
7
5219
by: Camellia | last post by:
hi all, I wrote a "table of powers" program and made the 5th power the highest, but when I tried to run the program I found a problem. Here's the output: Integer Square power 3rd power 4th power 5th ------- ------ --------- --------- --------- 1 1 1 1 1
22
6248
by: Alexandre Proulx | last post by:
I am trying to find 2 at the power of 601, but my calculator doesn't have a large enough screen, so I decided to make a program for my computer to do this, but when I get to a high number the computer only prints : 1.#INF00. Is there any way to do it? My code is the fallowing: #include <iostream> #include <stdio.h> #include <math.h> using namespace std; float a; float x; float y;
0
1596
by: tarlino | last post by:
Hi! I'm play with the sound generation (c++ and directX). Now I would like to manage same filter on my sample. But now I must to convert my audio buffer "BYTE" (from DirectX) to an arry of "short" and viceversa. I found this source: ************************************************************** double dPowI = ceil( log10( (double)iLen / ( ((double)wBitsPerSample / 8 ) + wChannels - 1 ) ) / log10( 2.0 ) ); int iNearTwoPower = (int)pow(...
2
1633
by: Netwatcher | last post by:
can somebody explain me where to put "{ }" and ";" symbols on a script? i did search the web but didn't find any explanation written in a way i can understand. example of a code that i tried and doesn't work <script Language="JavaScript"> function distance() } alert("Point One"); var x = prompt("Enter a X variable for the first point", "X"); var y = prompt("Enter a Y variable for the first point", "Y");
0
9687
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9541
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10484
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10251
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10228
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10027
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9072
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6805
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
3
2938
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.