Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract fractional part of double *efficiently* in C

Tags:

I'm looking to take an IEEE double and remove any integer part of it in the most efficient manner possible.

I want

1035 ->0 1045.23->0.23 253e-23=253e-23 

I do not care about properly handling denormals, infinities, or NaNs. I do not mind bit twiddling, as I know I am working with IEEE doubles, so it should work across machines.

Branchless code would be much preferred.

My first thought is (in pseudo code)

char exp=d.exponent; (set the last bit of the exponent to 1) d<<=exp*(exp>0); (& mask the last 52 bits of d) (shift d left until the last bit of the exponent is zero, decrementing exp each time) d.exponent=exp; 

But the problem is that I can't think of an efficient way to shift d left until the last bit of the exponent is zero, plus it seems it would need to output zero if all of the last bits weren't set. This seems to be related to the base 2 logarithm problem.

Help with this algorithm or any better ones would be much appreciated.

I should probably note that the reason I want branchless code is because I want it to efficiently vectorize.

like image 764
Jeremy Salwen Avatar asked Apr 08 '11 01:04

Jeremy Salwen


People also ask

How do you find a fractional part of a number in C?

In the C Programming Language, the modf function splits a floating-point value into an integer and a fractional part. The fraction is returned by the modf function and the integer part is stored in the iptr variable.

How do you find the fractional part of a function?

y={x}. For nonnegative real numbers, the fractional part is just the "part of the number after the decimal," e.g. { 3.64 } = 3.64 − ⌊ 3.64 ⌋ = 3.64 − 3 = 0.64.

What is fractional value in C?

Program Explanation (fractional number) printf is a function available(pre defined) in C library which is used to print the specified content in Monitor. Here it prints the value of the variable num. Format Specifier "%2f" prints value as Floating Point Number with 2digit Precision(. 00).


1 Answers

How about something simple?

double fraction = whole - ((long)whole); 

This just subtracts the integer portion of the double from the value itself, the remainder should be the fractional component. It's possible, of course, this could have some representation issues.

like image 60
Mark Elliot Avatar answered Sep 20 '22 06:09

Mark Elliot