Source file owl_base_maths.ml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
# 1 "src/base/maths/owl_base_maths.ml"
(*
 * OWL - an OCaml numerical library for scientific computing
 * Copyright (c) 2016-2018 Liang Wang <liang.wang@cl.cam.ac.uk>
 *)


let add x y = x +. y

let sub x y = x -. y

let mul x y = x *. y

let div x y = x /. y

let pow x y = x ** y

let atan2 x y = Pervasives.atan2 x y

let abs x = Pervasives.abs_float x

let neg x = ~-. x

let sqr x = x *. x

let sqrt x = Pervasives.sqrt x

let exp x = Pervasives.exp x

let log x = Pervasives.log x

let log2 x = (log x) /. (log 2.)

let log10 x = Pervasives.log10 x

let signum x =
  if ((compare x nan) = 0)
  then nan
  else (
    if (x > 0.)
    then 1.
    else (if x < 0. then (~-. 1.) else 0.)
  )

let floor x = Pervasives.floor x

let ceil x = Pervasives.ceil x

let round x = floor (x +. 0.5)

let trunc x = Pervasives.float_of_int (Pervasives.truncate x)

let sin x = Pervasives.sin x

let cos x = Pervasives.cos x

let tan x = Pervasives.tan x

let sinh x = Pervasives.sinh x

let cosh x = Pervasives.cosh x

let tanh x = Pervasives.tanh x

let asin x = Pervasives.asin x

let acos x = Pervasives.acos x

let atan x = Pervasives.atan x

(* asinh(x) is log(x + sqrt(x * x + 1)) *)
let asinh x = log (x +. (sqrt ((x *. x) +. 1.)))

(* acosh(x) is log(x + sqrt(x * x - 1)) *)
let acosh x = log (x +. (sqrt ((x *. x) -. 1.)))

(* atanh(x) is 1/2 * log((1 + x)/(1-x))) *)
let atanh x = 0.5 *. (log ((1. +. x) /. (1. -. x)))

let relu x = Pervasives.max 0. x

let sigmoid x = 1. /. (1. +. (log (~-. x)) )


(* Helper functions *)

let is_nan x = x = nan

let is_inf x = x = infinity || x = neg_infinity

let is_odd x = ((Pervasives.abs x) mod 2) = 1

let is_even x = (x mod 2) = 0

let is_pow2 x = (x <> 0) && (x land (x - 1) = 0)

let same_sign x y =
  if x >= 0. && y >= 0. then true
  else if x <= 0. && y <= 0. then true
  else false

let is_simplex x =
  let acc = ref 0. in
  let chk = ref true in
  (
    try
      Array.iter (fun a ->
        if a < 0. then (
          chk := false;
          raise Owl_exception.FOUND
        );
        acc := !acc +. a
      ) x;
    with exn -> ()
  );
  let df = abs_float (1. -. !acc) in
  if df > Owl_const.eps then chk := false;
  !chk