Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should I use Integers when I could just use floats or doubles in C#? [closed]

Tags:

c#

integer

Just learning C# at the moment.

I don't get why anyone would use Integers when they could use floats or doubles..

Floats will add/subtract whole numbers AND decimal numbers so why would anyone ever bother using a plain old integer?

Seems like floats or double will take care of anything that an Integer can do with the bonus of being able to handle . numbers too..

Thanks!

like image 949
GMax Jackson Avatar asked Nov 19 '25 01:11

GMax Jackson


1 Answers

The main reason is the same reason we often prefer to use integer fractions instead of fixed-precision decimals. With rational fractions, (1/3) times 3 is always 1. (1/3) plus (2/3) is always 1. (1/3) times 2 is (2/3).

Why? Because integer fractions are exact, just like integers are exact.

But with fixed-precision real numbers -- it's not so pretty. If (1/3) is .33333, then 3 times (1/3) will not be 1. And if (2/3) is .66666, then (1/3)+(2/3) will not be one. But if (2/3) is .66667, then (1/3) times 2 will not be (2/3) and 1 minus (1/3) will not be (2/3).

And, of course, you can't fix this by using more places. No number of decimal digits will allow you to represent (1/3) exactly.

Floating point is a fixed-precision real format, much like my fixed-precision decimals above. It doesn't always follow the naive rules you might expect. See the classic paper What Every Computer Scientist Should Know About Floating-Point Arithmetic.

To answer your question, to a first approximation, you should use integers whenever you possibly can and use floating point numbers only when you have to. And you should always remember that floating point numbers have limited precision and comparing two floating point numbers to see if they are equal can give results you might not expect.

like image 94
David Schwartz Avatar answered Nov 20 '25 16:11

David Schwartz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!