473,728 Members | 1,612 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 #1
15 11651
* Steven T. Hatton:
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.


There isn't such a function. There is the C library pow, the C++ library
valarray::pow and the C++ library complex::pow. Writing an unsigned integer
version should, as you state, be fairly trivial; why not just wrap the C pow?

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Jul 22 '05 #2
Steven T. Hatton 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.


Correct, there isn't one. There just isn't that much call for it
I would suspect. You don't have to raise a number to a very high
power before it starts overflowing.

You either code fast, or you need to learn how to read the docs faster.
It only took me about 20 seconds to load up the PDF of the Standard and
find in 26.5 where it says that these are the overloads for pow:
pow(float, float);
pow(float, int)
pow(double, double)
pow(double, int)
pow(long double, long double)
pow(long double, int)

I suspect your "integer pow" just iterates to do the exponentiation.
Pow typically uses a log (which is the only real way to do a fractional
exponent anyhow) which gives a more constant time.
Jul 22 '05 #3
Ron Natalie wrote:
Steven T. Hatton 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.
Correct, there isn't one. There just isn't that much call for it
I would suspect. You don't have to raise a number to a very high
power before it starts overflowing.


What I'm doing is strictly integer math. I seriously doubt I will get into
tensors of sufficient rank and order to overflow long int with the index
range.
You either code fast, or you need to learn how to read the docs faster.
It only took me about 20 seconds to load up the PDF of the Standard and
find in 26.5 where it says that these are the overloads for pow:
pow(float, float);
pow(float, int)
pow(double, double)
pow(double, int)
pow(long double, long double)
pow(long double, int)
I read that from the error output. I didn't need to grep the standard, but
I did look it up there as well. It tells me what /is/ there, but not what
isn't. Sometimes the Standard is a useful reference, and othertimes I run
into the parts where is redefines 'definition' and proceeds with the
redefined meaning in a less than consistent manner.
I suspect your "integer pow" just iterates to do the exponentiation.
No, I actually used compile time recursion.
Pow typically uses a log (which is the only real way to do a fractional
exponent anyhow) which gives a more constant time.


That's because you can add exponents in one operation rather than performing
n + m individual operations needed to do the brute force calculation.
Floating point numbers are represented in hardware in terms of significand
(base) and exponent. Addition and subtraction are actually more expensive
than multiplication and division.

I'm not sure what the cost of converting between floating point and 2's
complement is, but if I use pow() to do my integer math, I suspect it can
add up. I really have to test it before I can make a determination. This
is probably hardware sensitive more so than compiler or OS sensitive.
--
"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 #4
> > I suspect your "integer pow" just iterates to do the exponentiation.

No, I actually used compile time recursion.


Really? How interesting, can you please post the code for
the function?

Keith
Jul 22 '05 #5
Keith H Duggar wrote:
> I suspect your "integer pow" just iterates to do the exponentiation.


No, I actually used compile time recursion.


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/

I really don't know if this has any advantages, nor do I know if it is even
correct. I ran it through a few simple tests, but haven't revisited it
since. As I am working on my testing infrastructure.
/*************** *************** *************** *************** ***************
* 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. *
*************** *************** *************** *************** ***************/
#ifndef STH_TMATHPOWER_ H
#define STH_TMATHPOWER_ H
#include<stdexc ept>

namespace sth {
namespace tmath {

/**
@author Steven T. Hatton
*/
template <size_t Exponent_S, typename T>
class PowerOf
{
public:
static T eval(const T& base)
{
return base * PowerOf<Exponen t_S - 1, T>::eval(base) ;
}
};

template <typename T>
class PowerOf<1, T>
{
public:
static T eval(const T& base)
{
return base;
}
};

template <typename T>
class PowerOf<0, T>
{
public:
static T eval(const T& base)
{
if(!base)
{
throw std::logic_erro r(
"sth::tmath::Po werOf<0>(0) is an indeterminate form.");
}
return 1;
}
};

template <size_t Exponent_S, typename T>
T power(const T& base)
{
return PowerOf<Exponen t_S, T>::eval(base) ;
}
};
}

#endif

--
"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 #6
Steven T. Hatton wrote:

This is for the user to call instead of the member functions:
template <size_t Exponent_S, typename T>
T power(const T& base)
{
return PowerOf<Exponen t_S, T>::eval(base) ;
}

It's used like this:

size_t thirtytwo = power<5>::eval( 2);

It has the advantage of deducing template parameters.

NOTE: I should probably force the return type to be size_t. It may not be
as general, but for my purposes, it't more reasonable.
--
"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 #7
> Floating point numbers are represented in hardware in terms of significand
(base) and exponent.
I'm sure he appreciated that most elementary lesson. I'm
sure anyone who knows exponentiation is done using
logarithms knows how floating point numbers are stored.

Also, I forgot to point out earlier that
Addition and subtraction are actually more expensive
than multiplication and division.


is not correct. I know of no platform on which floating
point addition is slower than multiplication. The fastest
multiplications still take about 1.3 times the time of
addition for operations in isolation.

Now, under some caching conditions multiplication can
approach and even equal the speed of addition. That is why
many programmers simply consider floating addition and
multiplication to be about the same speed.

However, it is simply false to claim that addition is flatly
more expensive.

If however I'm wrong, and you have evidence to the contrary
please pass it along (along with your code for a compile
time recursive integer power function).
Jul 22 '05 #8
Keith H Duggar wrote:
Floating point numbers are represented in hardware in terms of
significand (base) and exponent.
I'm sure he appreciated that most elementary lesson. I'm
sure anyone who knows exponentiation is done using
logarithms knows how floating point numbers are stored.


I was making the distinction clear.
Also, I forgot to point out earlier that
Addition and subtraction are actually more expensive
than multiplication and division.
is not correct. I know of no platform on which floating
point addition is slower than multiplication. The fastest
multiplications still take about 1.3 times the time of
addition for operations in isolation.

Now, under some caching conditions multiplication can
approach and even equal the speed of addition. That is why
many programmers simply consider floating addition and
multiplication to be about the same speed.

However, it is simply false to claim that addition is flatly
more expensive.


My reason for saying that was based on what I learned a decade ago. 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. ..."
If however I'm wrong, and you have evidence to the contrary
please pass it along (along with your code for a compile
time recursive integer power function).


I already posted that.
--
"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 #9
"Steven T. Hatton" wrote:


My reason for saying that was based on what I learned a decade ago.
???
A decade ago?

A decade ago on most (if not all) CPU's the situation was:
multiplication was much more expensive then addition.
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?
On the other hand: I might not know all possible schemes for multiplication.

Hmm. Is there a way to study the entire section?
If not, what is the main point the above is based on?

The only thing I can think of is:
'simpler' is not used to mean: in terms of runtime efficiency
but is meant in terms of: creates less problems.
And the reason for this is: while in add/subtract one has to
first bring the exponents to the same number (which creates a
problem if there is a large difference) no such thing is necc.
in multiplication.
--
Karl Heinz Buchegger
kb******@gascad .at
Jul 22 '05 #10

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

Similar topics

0
1411
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
3464
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
4586
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
7873
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
8654
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
2352
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
5668
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
8899
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
9272
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
9196
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
9129
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
8124
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
4524
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...
0
4790
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2651
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2160
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.