Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
ldexp() function in C/C++
The ldexp() function in C computes the result of multiplying a floating-point number by an integral power of 2. It calculates x * 2^exp where x is a floating-point value and exp is an integer exponent.
Syntax
float ldexp(float x, int exp); double ldexp(double x, int exp); long double ldexp(long double x, int exp);
Parameters
- x − The floating-point base value
- exp − The integer exponent representing power of 2
Return Value
Returns x * 2^exp. If the result is too large to represent, it returns HUGE_VAL (infinity).
Example 1: Basic Usage
This example demonstrates basic usage of ldexp() function −
#include <stdio.h>
#include <math.h>
int main() {
double a = 10.0;
int exp = 2;
double result = ldexp(a, exp); // Calculates 10 * 2^2 = 10 * 4 = 40
printf("ldexp(%.1f, %d) = %.1f\n", a, exp, result);
return 0;
}
ldexp(10.0, 2) = 40.0
Example 2: Overflow Condition
When the result is too large to represent, ldexp() returns infinity −
#include <stdio.h>
#include <math.h>
int main() {
double a = 10.0;
int exp = 5000;
double result = ldexp(a, exp); // Very large exponent causes overflow
printf("ldexp(%.1f, %d) = %f\n", a, exp, result);
return 0;
}
ldexp(10.0, 5000) = inf
Example 3: Different Data Types
The ldexp() function works with different floating-point types −
#include <stdio.h>
#include <math.h>
int main() {
float f = 3.5f;
double d = 7.25;
printf("ldexp(%.1ff, 3) = %.1f\n", f, ldexp(f, 3));
printf("ldexp(%.2f, -2) = %.2f\n", d, ldexp(d, -2));
return 0;
}
ldexp(3.5f, 3) = 28.0 ldexp(7.25, -2) = 1.81
Key Points
- The function header
<math.h>must be included to useldexp(). - Negative exponents divide by powers of 2 instead of multiplying.
- The function is commonly used in floating-point arithmetic and scientific calculations.
Conclusion
The ldexp() function provides an efficient way to multiply floating-point numbers by powers of 2. It handles overflow gracefully by returning infinity when results exceed representable limits.
Advertisements
