Software > Software

Exponents in C?

(1/2) > >>

Commanderbob:
I have a dsPIC33FJ128GP710 and I use MikroC as my compiler. I did the graphing of a Sharp IR sensor and got

y = 359.56x^-0.8702

How do I enter that in C? The 359.56 is easy with floats but I have never used decimal exponents. Any suggestions?
Thanks,
Justin

bens:
Off the top of my head I don't know the best answer to this one, but I can suggest a few things for you to try:

1) look for a C math library that gives you a function like

float pow(float x, float n);

In all my programming experience I've been able to use prewritten libraries for exponentials, logarithms, trig functions, etc.

2) Search the web for such algorithms or look for a book such as Numerical Recipes for C.  I suspect the ideal algorithm is not a simple one and probably involves an iterative solution since raising to a decimal power like -.8702 is equivalent to computing the 10000th root of (1/x)^8702 (and I believe computing roots is where the difficulty arises).

3) If you can get by with an approximation of this formula, I suggest you create a lookup table by precomputing values spread out at fixed intervals along your domain of interest.  You can then obtain y for an arbitrary x by performing a linear interpolation on the interval in which x resides (basically, you're breaking up your continuous ideal curve into a bunch of short line segments that approximate the curve).  I think I remember hearing somewhere that this is how sine and cosine are often computed in software on platforms with limited computational power.  Or you could get fancier and perform some higher order fit to curve points to reduce the error.

Tsukubadaisei:
include math.h in your source the use pow(float, float)

Admin:
I second bens on his #3 point.

Doing float exponents take a lot of processing power, hence a lot of time on a tiny microcontroller.

You might just want to do:
y = 359.56x

and see if the error really matters or not. So I calculated error for you:

error:
(359.56*x^(-0.8702))/(359.56*x) , where x is between 0 and 255 (ADC reading)

Plotting it:
x=2, error is 27%
x=5, error is 4.9%
x=10, error is 1.3%
x=50, error is .07%

So in most cases, your error will be under 1%, which just isn't worth doing floats and exponents . . .

Commanderbob:
My ADC is 12bit. dsPIC33.
Thanks a lot I was looking under exp not pow. I am going to use a Gumstix to do this and I need it as close as possible so I will use the exponents.

Thanks,
Justin

Navigation

[0] Message Index

[#] Next page

Go to full version