Reputation: 120364
What is the minimum value d
such that...
f - d != f
f + d != f
...for any CGFloat
f
(except infinity)?
For example, it's not 1
.
CGFloat f = CGFLOAT_MAX;
CGFloat d = 1;
NSLog(@"%d", f - d != f); // Prints 0
Upvotes: 0
Views: 372
Reputation: 318955
The minimum value for d
depends on the value of f
.
The problem is that CGFloat
only supports a certain number of significant digits and not all floating point number are represented exactly.
The following is not exact results but meant to illustrate the problem.
If f
is 1.0
then d
might need to be something like 0.0000001
. But if f
is 1000000.0
(one million) then d
would need to be 0.1
.
Basically the value of d
must be within the significant digits of f
for the result to be noticeable.
Consider using NSDecimalNumber
to be able to fully represent large numbers eliminating this problem.
Upvotes: 0
Reputation: 33283
That would depend on the the definition of CGFLOAT on your platform.
Current platforms use either float (typically when compiling for 32-bit platforms) or double (typically when compiling for 64-bit platforms).
32 bit floats use 23 bits for the fraction, which means that d
would probably be around CGFLOAT_MAX/2^23
64 bit doubles use 52 bits for the fraction, which means that d
would probably be around CGFLOAT_MAX/2^52
Upvotes: 0
Reputation: 224556
If “any CGFLOAT
” truly means any value that a CGFLOAT
can take, then the answer is infinity. Otherwise, f
could be infinity (a legal value), and f-d
would equal f
for any finite value of d
.
If f
is limited to finite values, then d
is 2970 if CGFLOAT_IS_DOUBLE
is set and 2103 otherwise. This is because those are the smallest values required to cause a change when d
is added to the largest finite values that a CGFLOAT
could have.
These are undoubtedly not the values you are looking for. As Stephen Canon notes, what are you really trying to do?
Upvotes: 3
Reputation: 8180
The value such that
f - d != f
f + d != f
is not fixed for all possible floating point numbers. You've probably came to this conclusion your own because you can clearly see that for d=1 and f=5.0, f-d=4.0... but this doesn' work for CGFLOAT_MAX.
This is because of how floating point numbers are stored in memory, they are stored with a base and an exponent, so not all digits are being represented.
Upvotes: 0