简体   繁体   中英

C approximation functions

I am making some approximation functions for exp, log, and sqrt in C for java. I'm a little rusty on how pointers work -- is this grammar correct?

#include <math.h>
#include "QDMath.h"

JNIEXPORT jdouble JNICALL Java_QDMath_exp
  (JNIEnv *env, jclass class, jdouble val)
{
    jint tmp = (jint) (1512775 * val + 1072632447);
    jdouble p = 0.0;
    *(1 + (jint * ) &p) = tmp;
    return p;
}

JNIEXPORT jdouble JNICALL Java_QDMath_log
  (JNIEnv *env, jclass class, jdouble val)
{
    jint tmp = (*(1 + (jint *) &val));
    jdouble p = ((jdouble) tmp - 1072632447) / 1512775;
    return p;
}

JNIEXPORT jdouble JNICALL Java_QDMath_sqrt
  (JNIEnv *env, jclass class, jdouble val)
{
    jlong tmp = ((*(jlong *) &val) - 1065353216)>>1;
    return *(jdouble *) &tmp;
}

At a glance, the syntax looks correct (although a compiler would tell you quicker than we can).

However, what you're doing with them looks pretty grim. Reinterpreting double s as int s is platform dependent (think endianness and sizeof issues), and will also fall foul of "strict aliasing" rules.

In general this looks very wrong and raised some red flags for me, but you might be OK.

The use of the Java types is helping. If you were casting to an int , you would have problems on some machines because ints might be 32-bit or 64-bit. Using jint , it should always be 32-bit, so in that respect you are safe.

I'm still not entirely clear what you are attempting. For example, this line:

*(1 + (jint * ) &p) = tmp;

What you are saying to do is to take the address of p ( a double ), treat it as an Java integer address, and then add one to it. This would mean to take the location of the double and look 4 bytes into it... putting you somewhere in the fractional part of the IEEE encoded double .

Then you are setting that location to the value in tmp... which is an integer and not IEEE encoded.

Unless you are doing something incredibly clever by manipulating the bits of the double directly, what you are doing will produce meaningless results.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM