derek
derek

Reputation: 23

Unexpected behavior of if statement in OCaml

I am learning OCaml so maybe I am writing this if-statement wrong, but for this statement:

# if 0.3 -. 0.2 = 0.1 then ’a’ else ’b’;;

the output is:

- : char = 'b'

Shouldn't the output be 'a', since 0.3 - 0.2 = 0.1? The behavior is also the same when I write == instead of =.

Upvotes: 0

Views: 66

Answers (1)

Jeffrey Scofield
Jeffrey Scofield

Reputation: 66793

Floating point values can only represent decimal fractions approximately. So 0.3 -. 0.2 is very close to 0.1, but not exactly equal.

# 0.3 -. 0.2;;
- : float = 0.0999999999999999778

Understanding this is a rite of passage for programmers. Here's a site I found with some discussion: What Every Programmer Should Know about Floating Point.

As a side comment, you should never be using the == (physical equality) operator in ordinary computations. Example:

# 1.0 == 1.0;;
- : bool = false

This is a different problem. Floating values aren't that approximate :-)

The everyday, workhorse equality comparison operator is =. That's what you should use unless you have a specific reason not to.

Upvotes: 1

Related Questions