开发者

DBL_MAX & Max value of a double

This line:

NSLog(@"DBL_MAX: %f", DBL_MAX);

prints this very large value: 17976931348623157081452742373170435679807056752584499659891747680315726078002853876058955863276687817154045895351438246423432132688946418276846754670353751698604991057655128207624549009038932894407586850845513394230458323690322294816580855933212334827479

However, when I test a double value like this:

double test = 9999999999999999.0;
NSLog(@"test: %f", test);

I get this unexpected result:

test: 10000000000000000.000000

This appears to be the maximum number of digits 开发者_开发知识库that produce the expected result:

double test = 999999999999999.0;
NSLog(@"test: %f", test);

test: 999999999999999.000000

How can I work with higher positive fractions?

Thanks.


Unfortunately, I can't answer the question directly, as I don't understand what you mean by "How can I work with higher positive fractions?".

However, I can shed some light on what a floating-point number is ans what it isn't.

A floating-point number consists of:

  • A sign (plus or minus)
  • An exponent
  • A value (known as the "mantissa").

These are combined using a clever encoding typically into 32, 64, 80, or 128 bits. In addition, some special encodings are used to represent +-infinity, Not a Number (NaN), and +-Zero.

As the mantissa has a limited number of bits, your value can only have this number of significant bits. A really small floating-point number can represent values in the 10^-308 and and large one 10^308. However, any number can only have about 16 decimal digits.

On other words, the print-out if DBL_MAX does not corresponds the amount of information stored in the variable. For example, there is no way to represent the same number but with a ...7480 instead of ...7479 at the end.

So back to the question, in order to tell how to represent your values, you must describe what kind of values you want to represent. Are they really fractions (i.e. one integer divided by another integer), in that case you might want to represent this using two integers. If you want to represent really large values, you might want to use packages like http://gmplib.org


Floating point in C# doesn't produce accurate results all the time. There are numbers that cannot be represented in double, floats or decimals. You can improve your accuracy by using "decimal" instead of "double", but it still doesn't ensure that all numbers will be represented exactly.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜