Question

Need a pow() function without math.h

Asked by: tknudsen-qec

I'm tweaking a program that requires that I raise an integer to the power of a fraction: 3 ^ 1.4, etc.

The problem is that I cannot use the standard math.h pow() function as I'm having too many difficulties trying to include the library (there are function-name conflicts, particularly with "log", and I don't have leave to go and change all the conflicting function names in this program)

I made a bona-fide effort to rip the pow() function right out of the math.h library but eventually gave up.  (the math.h pow #define actually references itself as a parameter...as far as I can tell...neat)

Is there a custom-made pow() function that handles exponential powers I can use? I don't particularly care if it only returns integers (if it matters).  Alternately, if someone smarter than I has taken or can successfully export the standard version for use I'd be terribly pleased.

Thanks kindly

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-09-24 at 08:37:27ID24758851
Tags

C

,

functions

Topics

C Programming Language

,

Algorithms

Participating Experts
4
Points
500
Comments
22

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Problem with pow() function
    I need the result of a pow() calculation as an integer. I have been getting aqurate results whether the numbers within the pow() function were either double or int. I discovered what may be an interesting bug in this function. I am using the function like these examples; N...
  2. fractions
    How do you do fractions in Pascal? Does it require a function if so how would it be written? Also how can I aternately add and subtract a series of numbers i.e. (1-3+5-7+9.....)?
  3. HELP!!! Random numbers between A and B that are ex…
    Hi there, I am looking for serious help!!! with, Generating Random Numbers Between A and B that are Exponentially Distributed. I can generate an exponentially distributed random nubers from an uniform distribution BUT I DON"T KNOW HOW TO MAP IT BETWEEN THE RANGE A and B...
  4. pow(10,x) implementation!
    hi, could anybody tell me, how can i implement pow(10,x) function, where x can be double? ofcourse, i want to minimize use of library functions to speedup the process?

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: _phoenix_Posted on 2009-09-24 at 09:17:49ID: 25415005

What do you have coded so far? I think there is already a solution in the EE.

http://www.experts-exchange.com/Programming/Languages/C/Q_20786971.html?sfQueryTermInfo=1+function+pow

 

by: Infinity08Posted on 2009-09-24 at 09:19:45ID: 25415033

>> there are function-name conflicts, particularly with "log", and I don't have leave to go and change all the conflicting function names in this program

I would make the time to do that, since you'll have to make the changes anyway if you use your own code to implement log and pow. Conflicts aren't magically resolved by providing a different implementation ;)

Or maybe I'm misunderstanding the issue.

In any case, if you want your own implementation of pow, you could do exp(b * log(a)) which is the same as pow(a, b).

Or you can take the code from glibc compiler for example.

 

by: tknudsen-qecPosted on 2009-09-24 at 09:30:47ID: 25415148

Greetings Phoenix, thanks for taking the time to respond.

I had reviewed that response; unfortunately sunnycoder failed to mention that the #define referenced other #defines which he/she didn't include (I see __tgmath_real_type  at a glance).   The "accepted solution" was a forced-accept which led to a broken link (or useless link anyway)

Honestly I tried to do exactly that last night but failed because I also grabbed the #define pow() part which seemed to reference itself and wouldn't compile.  If necessary I'm going to try again tonight with just the # define __TGMATH_BINARY_REAL_IMAG(Val1, Val2, Fct, Cfct) code and not the #define pow() part if it isn't critical.

 

by: tknudsen-qecPosted on 2009-09-24 at 09:34:44ID: 25415197

Hi Infinity08, thanks for taking the time to respond.

For once, my reluctance to do as you suggest isn't simply rank laziness.  I really don't have liberty to change the name of the conflicting functions.

I'd be very satisfied with a "copy" of the standard glibc version renamed to pow_stolen() or something to be honest, therefore, conflict magically resolved.  (Note I don't 'need' the math.h library itself, just the one function)

Your alternate solutions require exp and log which are also parts of math.h :)

Thanks kindly!

 

by: _phoenix_Posted on 2009-09-24 at 10:08:36ID: 25415498

In the link I posted, the pow function is written, however it's not just to cut and paste in the code, that's part of the glibc that I8 is mentioning.

As for the link, I have found the file which I'm attaching for you to review, however is just the math part, no code is written in the file.

I would use the log implementing a series, also the exp can be defined as a Taylor series.

 

by: Infinity08Posted on 2009-09-24 at 10:39:22ID: 25415769

>> Your alternate solutions require exp and log which are also parts of math.h :)

I know. But you mentioned conflicts with log, so I assumed that you already had your own implementation for that.

In any case, it's relatively easy to implement the exp and log functions.

The exp function can be approximated to arbitrary precision using Euler's continued fraction for example :

        http://en.wikipedia.org/wiki/Exponential_function#Continued_fractions_for_ex

The log function can be approximated to arbitrary precision using a series like :

        http://en.wikipedia.org/wiki/Logarithm#More_efficient_series

The ease of computation of both the exp and log functions is the reason why I suggested using that formula to implement pow.

 

by: Infinity08Posted on 2009-09-24 at 10:40:08ID: 25415774

>> I would use the log implementing a series, also the exp can be defined as a Taylor series.

Precisely :)

 

by: thehagmanPosted on 2009-09-24 at 10:49:30ID: 25415866

Since your code will hardly be redistributable if it conflicts with naming conventions in math.h, I assume you are targeting only for a single type of CPU and not for the "general audience".
In this case a bit of assembler might help, esp. for Intel CPUs, the F2XM1, FYL2X, FYL2XP1 instructions (they compute 2^x-1, y*ld(x), y*ld(x+1), hence the instruction sequcne for x^y is: load y, load x, FYL2X, F2XM1, FLD1, FADDP)

 

by: tknudsen-qecPosted on 2009-09-24 at 11:25:50ID: 25416225

Bit of explanation:  The code isn't my own and I can only change parts of it.  The code does not include many standard header files.  It obviously does not include math.h (to my despair).

I8: conflicts with log are by name only: the application "logs" things in hundreds of places throughout the code calling a "log()" function (not my devising.)

Thus far the responses have been far above my level of comprehension and I'm concerned about wasting everyone's time.   Is there a way I can flag the question to indicate a lower level of knowledge and garner responses tailored to my level?  Ideally I'm hoping to see a response including an actual function/macro/define that performs x^y (and if that's irresponsible I'll kill the question and figure out how to ensure everyone who has responded gets a share of the points.)


 

by: tknudsen-qecPosted on 2009-09-24 at 11:27:59ID: 25416251

Ideally I'm hoping to see a response including an actual function/macro/define that performs x^y WHERE y can be a fractional number (I've seen integer-only functions that work just fine)

 

by: Infinity08Posted on 2009-09-24 at 12:37:21ID: 25416936

>> Thus far the responses have been far above my level of comprehension

My apologies for that. I'll be a bit more explicit from now on ;)

Before continuing, I just thought about a different approach that requires a lot less work (it still uses the math.h library), so you might prefer it :)

What if you just write a wrapper function around the math.h pow function (and similarly for any other math.h functions you need), and use that in the rest of your code ? ie. :

/* --- mymath.h --- */
 
#ifndef MYMATH_H
#define MYMATH_H
 
double mypow(double base, double exponent);
 
#endif /* MYMATH_H */
 
 
/* --- mymath.c --- */
 
#include "mymath.h"
 
#include <math.h>
 
double mypow(double base, double exponent) {
  return pow(base, exponent);
}
 
 
 
/* --- everywhere you need to use the pow function : --- */
 
#include "mymath.h"
 
double result = mypow(3.0, 1.4);

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:

Select allOpen in new window

 

by: tknudsen-qecPosted on 2009-09-24 at 12:48:18ID: 25417070

I8,

You're very patient, thank you.  You don't think including mymath.h, which includes math.h, won't simply bring up the same conflicts?  (I won't be able to confirm either way for 3 hours).  I gather I'd also need to include mymath.c in the Makefile.

This is just the sort of clever response I was hoping for, I'm crossing my fingers it works :)

 

by: Infinity08Posted on 2009-09-24 at 12:50:56ID: 25417104

>> You don't think including mymath.h, which includes math.h

The thing is that mymath.h doesn't include math.h. The only file that includes math.h is mymath.c. That way, it's completely hidden from the rest of the code.


>> I gather I'd also need to include mymath.c in the Makefile.

Indeed.


>> I'm crossing my fingers it works :)

Let me know :)

 

by: _phoenix_Posted on 2009-09-24 at 12:54:54ID: 25417148

Ok,

here is what I found... and I think it's going to work for you :)...

Here is the link when I found the library, no time to implement a pow function at work, this one seems to work fine.

http://www.hxa.name/articles/content/fast-pow-adjustable_hxa7241_2007.html

you will be able to download the following file that implements the pow function:
fast-pow-adjustable_hxa7241_2007.zip

Hope it helps

 

by: _phoenix_Posted on 2009-09-24 at 12:56:41ID: 25417174

Hey l8, that's just a trick :P, but well, it will work to trick someone that doesn't know that the math.h is linked to that library.

 

by: mrdoe1Posted on 2009-09-24 at 13:00:42ID: 25417220

Actually the link in the mentioned forced accept that you referenced (first few posts) wasn't broken, just outdated.  Here's a new link to the same PDF

http://math.ucalgary.ca/~kwooding/papers/hardware/gordon98survey.pdf

 

by: _phoenix_Posted on 2009-09-24 at 13:03:50ID: 25417251

Hey l8, what you think about the link I posted for the library, seems fine to me :)...

 

by: Infinity08Posted on 2009-09-24 at 13:11:19ID: 25417330

>> Hey l8, that's just a trick :P, but well, it will work to trick someone that doesn't know that the math.h is linked to that library.

I'm not sure what you mean. But it's not a "trick" ... it's a valid design pattern called 'adapter'.

It's also not intended to "trick" somebody - it's intended to provide an easy way to get around the limitation described by tknudsen-qec.


Note that the problem was not with the math library, but with the name conflicts (introduced by including the math.h header file in the same file that uses a conflicting function).

 

by: thehagmanPosted on 2009-09-24 at 13:11:58ID: 25417339

In case you are only developing for x86 cpu's (and use the gnu compiler), see attached code that implements pow() using assembler.

And here's yet another way to include <math.h> without disturbing log:

#define log some_obscure_name
#include <math.h>
#undef log

#include <stdio.h>
 
float mypow(float x, float y) {
        float result;
        asm __volatile(
                "flds %2; flds %1; fyl2x;"
                "fld %%st;" //"flds %2; flds %1; fyl2x;"
                "frndint;fxch %%st(1);"
                "fsub %%st(1),%%st; f2xm1;"
                "fld1;faddp;fscale;fstp %0;faddp;"
                : "=g"(result)
                : "g"(x), "g"(y)
        );
        return result;
}
 
int main() {
        int i;
        float y = 3.14;
        for (i=1; i<10; ++i) {
                printf("%d ^ %f == %f\n", i,y,mypow(i,y));
        }
        return 0;
}
 
 
Output:
1 ^ 3.140000 == 1.000000
2 ^ 3.140000 == 8.815242
3 ^ 3.140000 == 31.489140
4 ^ 3.140000 == 77.708481
5 ^ 3.140000 == 156.590668
6 ^ 3.140000 == 277.584381
7 ^ 3.140000 == 450.409912
8 ^ 3.140000 == 685.019043
9 ^ 3.140000 == 991.565918
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:

Select allOpen in new window

 

by: Infinity08Posted on 2009-09-24 at 13:14:52ID: 25417387

>> Hey l8, what you think about the link I posted for the library, seems fine to me :)...

It could be (i didn't look at it in detail). But I honestly prefer to use the math.h library whenever possible - it's easier, more portable, and probably more efficient too.

 

by: tknudsen-qecPosted on 2009-09-25 at 06:20:17ID: 31633059

Infinity08

I would have responded to this sooner but our satellite linkup failed in a storm last night.

I'm pleased that not only do I have access to the pow() function, I can hook into any of the math functions as needed.

I asked for change for the bus and you handed me a blank cheque.  THANKS :)

 

by: Infinity08Posted on 2009-09-25 at 09:46:52ID: 25424689

>> I'm pleased that not only do I have access to the pow() function, I can hook into any of the math functions as needed.

Precisely. You can apply this 'adapter' design pattern anywhere where you cannot use the original interface for some reason (due to name clashes like in your case for example).

>> I asked for change for the bus and you handed me a blank cheque. THANKS :)

You are very welcome :)

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...