473,786 Members | 2,375 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

An exponentiation function for int?

Did I mess something along the way, or is there no function in Standard C++
to raise an (unsigned) int to a power of (unsigned) int returning
(unsigned) int? I never gave this a second thought until today. I tried to
do it, and discovered <cmath> std::pow() only takes floating point types
for the first argument. Sure I could write one. I could have written at
least 3 fundamentally differnet versions in the time it took to discover
there isn't such a function.
--
"If our hypothesis is about anything and not about some one or more
particular things, then our deductions constitute mathematics. Thus
mathematics may be defined as the subject in which we never know what we
are talking about, nor whether what we are saying is true." - Bertrand
Russell

Jul 22 '05
15 11657
> > Really? How interesting, can you please post the code for
the function?

Keith


This is based on ideas from _C++_Templates_ The_Complet_Gui de_

http://www.josuttis.com/tmplbook/

....

Not to quibble, but this isn't really a "function" is? It is
a class implementation that happens to have a function you
call. That's why I asked you to post the code because had you
built a compile time recursive function that would have been
most unique. However, had you said you had a compile time
recursive class that implements pow I would have pointed you
to search the google group archives for

"pow() with integer exponents"

which would take you to

http://groups.google.com/groups?hl=e...5252B%25252B.*

where they discuss a few solutions and the tradeoffs. In
addition, Cy Edmunds posted a generic solution which is
actually faster (in terms of multiplication count) than the
one you posted. Your solution does not utilize repeated
squaring (an often used concept) to reduce the number of
multiplications form linear (as yours is) to something closer
to logarithmic. Cy's solution doesn't handle the general
case of repeated squaring but he does optimize for some of
the small powers.

The iterative solution posted by Nejat Aydin implements
repeated squaring and will be far faster than either generic
solution for large powers (and probably even small powers).
You could implement a similar scheme using compile time
recursion if you wish but for large powers this will lead to
serious code bloat and of course will be limited to compile
time powers only.
Jul 22 '05 #11
Karl Heinz Buchegger wrote:
"Steven T. Hatton" wrote:

Perhaps
I should have worded my statement more clearly. The way Stallings put it
in his _Computer_Organ ization_and_Arc hitecture_3rd_E d_ is "Floating-point
multiplication and division are much simpler processes than addition and
subtraction, as the following discussion indicates. ..."


That doesn't sound right. It has the smell of some nasty and weird
argumentation.
For one: All schemes I know for multiplcation require some additions.
So in a sense addition is a building block for multiplication. How can
addition then be slower the multiplication?


With fp multiplication you're adding exponent with 2's complement (or
similar) addition. With fp addition, you have to play around with the
exponents and the significands (more).

--
"If our hypothesis is about anything and not about some one or more
particular things, then our deductions constitute mathematics. Thus
mathematics may be defined as the subject in which we never know what we
are talking about, nor whether what we are saying is true." - Bertrand
Russell

Jul 22 '05 #12

"Steven T. Hatton" <su******@setid ava.kushan.aa> wrote in message
news:u8******** ************@sp eakeasy.net...
Karl Heinz Buchegger wrote:
"Steven T. Hatton" wrote:

Perhaps
I should have worded my statement more clearly. The way Stallings put
it
in his _Computer_Organ ization_and_Arc hitecture_3rd_E d_ is
"Floating-point
multiplication and division are much simpler processes than addition and
subtraction, as the following discussion indicates. ..."


That doesn't sound right. It has the smell of some nasty and weird
argumentation.
For one: All schemes I know for multiplcation require some additions.
So in a sense addition is a building block for multiplication. How can
addition then be slower the multiplication?


With fp multiplication you're adding exponent with 2's complement (or
similar) addition.


But that's not *all* you're doing! That's just how the adjustment for
differing exponents is made. You still have to multiply the mantissas,
which in general involves a series of additions. Assuming for simplicity
that the operations were done in decimal instead of binary, consider
multiplying 3.0 (3e0) and 5.0 (5e0) versus 3.0 (3e0) and 0.5 (5e-1). The
exponent addition trick is simply how you determine the placement of the
final decimal point (resulting in 15.0 (15e0) versus 1.5 (15e-1)). The FPU
still has to multiply the 3 and the 5, regardless.

Addition only requires the one addition for the mantissa, although it may
have to first adjust the exponents.

Even though the multiplication is likely done in the FPU hardware, it
probably still involves a loop of the output back to the input of the
registers, and repeating of additions of the contents. And that repeated
addition is what will eat your clock cycles.

Granted, for some specific values, multiplying two values may (possibly) end
up faster than adding those same two values. But in the general case,
that's not going to be true.
-Howard
Jul 22 '05 #13
Keith H Duggar wrote:
> Really? How interesting, can you please post the code for
> the function?
>
> Keith


This is based on ideas from _C++_Templates_ The_Complet_Gui de_

http://www.josuttis.com/tmplbook/

...

Not to quibble, but this isn't really a "function" is? It is
a class implementation that happens to have a function you
call. That's why I asked you to post the code because had you
built a compile time recursive function that would have been
most unique.


I never said it was a function. But I believe what you end up with is
pretty much a function built at compile-time using recursion. It only uses
static members, and I suspect it's pretty much loaded and executed in once
chunk. I haven't read that discussion yet.

In this version I basically used a binary tree, but reused the calculations
which would have been identical. If you compile and run the program, you
will have done as much testing as I have.

/*************** *************** *************** *************** ***************
* Copyright (C) 2004 by Steven T. Hatton *
* ha*****@globals ymmetry.com *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
*************** *************** *************** *************** ***************/
#include <iostream>
#include <iomanip>
#include <stdexcept>

using std::cout;
using std::logic_erro r;

template<size_t S>
struct Pwr{
inline static size_t pwr(const size_t& b)
{
size_t p = Pwr<S/2>::pwr(b);
return (S & 1) ? p * p * b : p * p;
}
};

template<>
struct Pwr<1>{
inline static size_t pwr(const size_t& b) { return b; }
};

// NOTE: I'm not handling Pwr<0>, but it's trivial.

template<size_t S>
struct Powers{
inline static size_t power(const size_t& b)
{
cout << b << "^" << S << " = " << std::setw(8) << Pwr<S>::pwr(b) << "
";
return Powers<S-1>::power(b);
}
};

template<>
struct Powers<0>{
inline static size_t power(const size_t& b)
{
if(!b){ throw logic_error("ER ROR: indeterminate form 0^0 "); }
cout << "\n";
return 0;
}
};
int main()
{
for(size_t s = 1; s < 10; s++)
{
Powers<5>::powe r(s);
}

return 0;
}

--
"If our hypothesis is about anything and not about some one or more
particular things, then our deductions constitute mathematics. Thus
mathematics may be defined as the subject in which we never know what we
are talking about, nor whether what we are saying is true." - Bertrand
Russell

Jul 22 '05 #14
On Wed, 13 Oct 2004 11:38:45 -0400, "Steven T. Hatton"
<su******@setid ava.kushan.aa> wrote:
Did I mess something along the way, or is there no function in Standard C++
to raise an (unsigned) int to a power of (unsigned) int returning
(unsigned) int? I never gave this a second thought until today. I tried to
do it, and discovered <cmath> std::pow() only takes floating point types
for the first argument. Sure I could write one. I could have written at
least 3 fundamentally differnet versions in the time it took to discover
there isn't such a function.


Are you pressed for execution speed of this function?

J.

Jul 22 '05 #15
JXStern wrote:
On Wed, 13 Oct 2004 11:38:45 -0400, "Steven T. Hatton"
<su******@setid ava.kushan.aa> wrote:
Did I mess something along the way, or is there no function in Standard
C++ to raise an (unsigned) int to a power of (unsigned) int returning
(unsigned) int? I never gave this a second thought until today. I tried
to do it, and discovered <cmath> std::pow() only takes floating point
types
for the first argument. Sure I could write one. I could have written at
least 3 fundamentally differnet versions in the time it took to discover
there isn't such a function.


Are you pressed for execution speed of this function?

J.

I've already far surpassed what my immediate needs are. But the exercise of
trying to optimize an unsigned int exponentiation function has paid off in
a big way. I really had no intention of getting into this problem so
deeply. But since it was interesting, and it allowed me to explore many
aspects of template metaprogramming , I pursued it.

As for why I originally wanted the function, I simply don't like using type
conversions that are potentially lossy, nor do I like casting with anything
but a dynamic cast. I was working with unsigned int - size_t to be more
specific. I didn't like the idea of converting back and forth between
integer and floating point representations .

I've discovered that I can store all my calculations in a single static base
class, and reuse the results, so speed of an int power function has become
nothing more than an academic exercise at this point.

--
"If our hypothesis is about anything and not about some one or more
particular things, then our deductions constitute mathematics. Thus
mathematics may be defined as the subject in which we never know what we
are talking about, nor whether what we are saying is true." - Bertrand
Russell

Jul 22 '05 #16

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

Similar topics

0
1415
by: Jeff Davis | last post by:
I was doing some thinking about exponentiation algorithms along with a friend, and I happened upon some interesting results. Particularly, I was able to outperform the ** operator in at least one case, with a recursive algorithm. This leads me to believe that perhaps the ** operator should tune it's algorithm based on inputs or some such thing. Here is my data: >>> def h(b,e): .... if(e==0): return 1 .... if(e==1): return b
5
3468
by: PeteCresswell | last post by:
----------------------------------------------------------------- Sub Sheesh() Dim myYears As Double Dim myRawCumulative As Double Dim myAnnualizedROR As Double myYears = 1.25 myRawCumulative = -9.24161581346505 myAnnualizedROR = ((myRawCumulative ^ (1 / myYears)) - 1)
2
4588
by: David Laub | last post by:
I know there is no C# exponentiation operator. But since the double class is sealed, there seems no way to add the operator override without creating a new class which uses containment (of a double value) This seems a major pain, and would probably wind up being more syntactically messy than just calling Math.Pow(x,y) Surely greater minds than I have already wrestled with this problem...
3
7875
by: James McGivney | last post by:
What is happening here ? long longg = 5; longg = longg + (2 ^ 8); the answer should be 5 + 256 or 261 but at the end of the above operation C# returns longg = 5 + 10 or 15
67
8671
by: carlos | last post by:
Curious: Why wasnt a primitive exponentiation operator not added to C99? And, are there requests to do so in the next std revision? Justification for doing so: C and C++ are increasingly used in low-level numerical computations, replacing Fortran in newer projects. Check, for example, sourceforge.net or freshmeat.net But neither language offers a primitive exp operator.
7
2356
by: elventear | last post by:
Hi, I am the in the need to do some numerical calculations that involve real numbers that are larger than what the native float can handle. I've tried to use Decimal, but I've found one main obstacle that I don't know how to sort. I need to do exponentiation with real exponents, but it seems that Decimal does not support non integer exponents.
8
5675
by: grahamhow424 | last post by:
Hi I am trying to figure out how to duplicate a, financial, calculation that uses the caret, Exponentiation. Here's the formula... A = 0.0755 B = 34 C = 50000
0
9647
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
9492
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,...
1
10108
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
8988
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...
1
7510
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5397
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4064
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3668
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2894
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.