Compare float list

I wrote the code:

let rec compareVs v1 v2 =
 if List.length v1 == 0 then
  true
 else
  ((match v1 with [] -> 0. | h::l -> h) == (match v2 with [] -> 0. | h::l -> h)) && 
  (compareVs(match v1 with [] -> [] | h::l -> l) (match v2 with [] -> [] | h::l -> l))

And launched it:

# compareVs [0.1;0.1] [0.1;0.1];;
- : bool = false

Cannot seem to find the problem. Please, help.

EDIT

Problem seams for floating point comparisons:

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

How else can we compare float in ocaml?

+3
source share
2 answers

Use =, not ==.

Floats are reference types in ocaml and ==checks for reference equality. Therefore it 0.1 == 0.1is false.

As a rule, you almost always want to use =, not ==to compare two values.

, true . , , true , , , - .

List.length , , (-, O (n), O (1) ). .

:

let rec compareVs v1 v2 = match v1, v2 with
| [], []       -> true
| [], _
| _, []        -> false
| x::xs, y::ys -> x = y && compareVs xs ys

, , , v1 = v2 .

+11

Sepp2k , ( ) :

epsilon, float. >., .

let epsilon = 1.0e-10
let (=.) a b = (abs_float (a-.b)) < epsilon

, classify_float pervasives. , NAN =. , .

, ( , epsilon, ). , NAN-NAN. , .

    let (=.) a b = match classify_float ( a -. b ) with
        | FP_infinite  | FP_nan | FP_normal -> false
        | FP_subnormal | FP_zero -> true
+5

Source: https://habr.com/ru/post/1770932/


All Articles