Using Floats
- Almost anything you can do to an int you can do to a
float: assignment, addition, subtraction, multiplication, division,
and comparison with ==, !=, <=, >=, <, and > are all valid.
One exception is that there is no modulus operator %.
- Floating point constants must include a decimal point (or they are
assumed to be int) and may use either e or E
to express exponents: 6.022e23, for example.
- As we saw before, x is declared to be a float variable
by the statement float x;. You can print x by using
a "%f" field in printf, and read it by using a "%f" field in
scanf.
- "Floating point numbers are like piles of sand. Everytime you use one,
you lose a little bit." Here are some things to look out for when using
floating point numbers:
- big number + little number = big number.
- 0.2 = 0.199999999....
- 0.2 != 0.1 + 0.1
- (10^30 + -10^30 ) + 1 != 10^30 + ( -10^30 + 1 )
- rounded number near x - another rounded number near x = noise. [Or why
2c/(-b+sqrt(b^2-4ac)) is better than (-b - sqrt(b^2-4ac))/2a.]
- 1/MAX_DOUBLE = 0.0 [underflow]
- x/(x^2 + 1) versus 1/(x + 1/x). [premature overflow]
- +-INF, NaN, +-0.
Next Slide