Click here to Skip to main content
15,891,027 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
Assuming i have some decimal fraction of unknown length AND without the integral part:
0.123 [3]
OR
0.0200405 [7]
OR
0.0000000987 [10]
etc

I have 'that' fraction as a C string (after convertion with the sprintf) AND as a long double (after using modfl). I take word that in a columns because this two fractions can easily differ (due to the precison penalty involved).

What I have tried:

There is obvious way to do that using a simple cycle, but may be there is a better way to do this? I am thinking of using binary search, which should probably be faster (AND also mostly ignores precison penalty), reducing time complexity form O(n) to the O(log(n)), but is there a way to do it with the constant complexity (for example, if a have an integral number, i can simply use log10 intrinstic)?
Posted
Updated 21-Mar-16 10:54am
Comments
Sergey Alexandrovich Kryukov 21-Mar-16 16:14pm    
Why? In general case, this length will be infinite, or, more exactly, not accurately given by any particular floating-point representation, like in 1/3. In other words, the problem is ill-posed (if the input is some number, not string).
Why? If this is for some kind of output formatting, the whole idea is wrong. What exactly do you want to achieve, ultimately?
—SA
Patrice T 21-Mar-16 16:55pm    
Why do you worry about this ?
sprintf takes much more time.
Shvetsov Evgeniy 21-Mar-16 17:10pm    
"Why" what? 9/8 gives 1,125 while 4/5 gives 0,8 and 2/1 gives 2.0, do y see there some 'infinity'? 64 bit IEE754 floating point gives only up to 15–17 significant decimal digits precision, so 1/3 as a decimal fraction can't be longer then 17 digits (as a number) anyway. I am upgrading a convertion module form my library and i want it to be implemented in the efficient way, thats exactly what i want.
[no name] 22-Mar-16 19:24pm    
How many digits do you expect to see for 1/3, e, or PI?

On a serious side, have you considered a rational number type instead of floating point?

1 solution

Quote:
I have 'that' fraction as a C string
Just calc the length of string minus 2 and you are done. There is no solution in constant time.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900