frexp()

[Math]
double frexp(double x, int *pointer);

Description

This function breaks a floating-point number x into a normalized fraction and an integral power of 2. It stores the integer in the location pointed to by pointer.

If x is a normal floating-point number, this function returns the value v, such that v has a magnitude in the interval [0.5, 1) or zero, and x equals v times 2 raised to the power of pointer. If x is zero, both parts of the result are zero. If x is not a finite number, this function returns x as is and stores zero by pointer.

Parameters

x: The value to calculate the normalized fraction and the integral power of 2. pointer: The address of a variable to store the integral power of 2.

Returns

The fractional part of x.

Example Code

The code reads the value of two potentiometers connected to pins INX and INY and place the normalized fraction of x on pin OUT and the integral power of 2 on pin OUT2.

void setup() {
    pinLabel(0, "INY");  // set the label of pin 0 to "INY"
    pinLabel(1, "INX");  // set the label of pin 1 to "INX"
    pinLabel(2, "OUT");  // set the label of pin 2 to "OUT"
    pinMode(2, OUTPUT);  // set pin 2 as output
    pinLabel(3, "OUT2"); // set the label of pin 3 to "OUT2"
    pinMode(3, OUTPUT);  // set pin 3 as output

    pinLabel(4, "VCC");  // set the label of pin 4 to "VCC"
    powerPin(4);         // set pin 4 as power pin
    pinLabel(5, "GND");  // set the label of pin 5 to "GND"
    groundPin(5);        // set pin 5 as ground pin
}

void loop() {
    // read the value of the potentiometers
    int val_x = analogRead(0);
    int val_y = analogRead(1);
    // map the value of the potentiometers from 0 to 1023
    // to the range of 0 to 10
    double x = map(val_x, 0, 1023, 0, 10);
    double y = map(val_y, 0, 1023, 0, 10);
    // calculate the normalized fraction of x
    double z;
    int exponent;
    z = frexp(x, &exponent);
    // map the value of z from 0.5 to 1 to 0 to 1023
    int pwm = (int) map(z, 0.5, 1, 0, 1023);
    // write the value of pwm to pin 2
    analogWrite(2, pwm);
    // map the value of exponent from -10 to 10 to 0 to 1023
    pwm = (int) map(exponent, -10, 10, 0, 1023);
    // write the value of pwm to pin 3
    analogWrite(3, pwm);
}

Notes and Warnings

This function permits a zero pointer as a directive to skip a storing the exponent.