Float.Array(3)
π¦ Float.Array(3) β OCaml library π¦
okay bestie, welcome to the OCaml library section, page Float.Array(3) β this one is all about float arrays with a packed representation, and it is lowkey iconic for numerical code. let's get into it π
π NAME π
Float.Array β Float arrays with packed representation. that's the whole vibe, no cap.
π¦ Module π¦
the module name in the source is literally:
Module Float.Array
so yeah, this page is documenting Float.Array. π«Ά
πΈ Documentation πΈ
inside the docs there's this stub:
Module Array
: sig end
and then the real content starts:
Float arrays with packed representation. β¨
type t = floatarray
this is the type of "flat" float arrays. π
a floatarray is an array data structure that contains a fixed number of elements of type float. the elements of a floatarray are guaranteed to be stored contiguously in memory, without any boxing. that's the whole point β it's packed and tidy. π
currently, the built-in type float array is optimized by default to also use an unboxed representation. however, this optimization may be disabled at configure-time when building the compiler. furthermore, operations on floatarray are a bit more efficient than those on float array, which require an extra dynamic check. so floatarray is giving main character energy in the efficiency department. π
array literals of type floatarray can be written using the same syntax as those of type float array as long as there is enough typing information in the environment so that the compiler can disambiguate between the two cases. see Section 12.25 'Type-directed disambiguation of array literals' of the manual for more details. π§
Since 4.08 β
val length : t -> intβ returns the length (number of elements) of the given floatarray. literally just the count, bestie. π’val get : t -> int -> floatβget a nreturns the element numbernof floatarraya. RaisesInvalid_argumentifnis outside the range0to(length a - 1). don't try to be cute with out-of-bounds indices, it will not slay. πval set : t -> int -> float -> unitβset a n xmodifies floatarrayain place, replacing element numbernwithx. RaisesInvalid_argumentifnis outside the range0to(length a - 1). same boundaries, same drama. πval make : int -> float -> tβmake n xreturns a fresh floatarray of lengthn, initialized withx. RaisesInvalid_argumentifn < 0orn > Sys.max_floatarray_length. πval create : int -> tβcreate nreturns a fresh floatarray of lengthn, with uninitialized data. RaisesInvalid_argumentifn < 0orn > Sys.max_floatarray_length. uninitialized means exactly that β don't assume it's zeroed, bestie. πval init : int -> (int -> float) -> tβinit n freturns a fresh floatarray of lengthn, with element numberiinitialized to the result off i. in other terms,init n ftabulates the results offapplied to the integers0ton-1. RaisesInvalid_argumentifn < 0orn > Sys.max_floatarray_length. πval make_matrix : int -> int -> float -> t arrayβmake_matrix dimx dimy ereturns a two-dimensional array (an array of arrays) with first dimensiondimxand second dimensiondimy, where all elements are initialized withe. Since5.2. RaisesInvalid_argumentifdimxordimyis negative or greater thanSys.max_floatarray_length. β¨val init_matrix : int -> int -> (int -> int -> float) -> t arrayβinit_matrix dimx dimy freturns a two-dimensional array (an array of arrays) with first dimensiondimxand second dimensiondimy, where the element at index( x,y )is initialized withf x y. Since5.2. RaisesInvalid_argumentifdimxordimyis negative or greater thanSys.max_floatarray_length. π¦val append : t -> t -> tβappend v1 v2returns a fresh floatarray containing the concatenation of the floatarraysv1andv2. RaisesInvalid_argumentiflength v1 + length v2 > Sys.max_floatarray_length. πval concat : t list -> tβ same asFloat.Array.append, but concatenates a list of floatarrays. group-chat merge, but for arrays. π«Άval sub : t -> int -> int -> tβsub a pos lenreturns a fresh floatarray of lengthlen, containing the elements numberpostopos + len - 1of floatarraya. RaisesInvalid_argumentifposandlendo not designate a valid subarray ofa; that is, ifpos < 0, orlen < 0, orpos + len > length a. slice responsibly. π₯val copy : t -> tβcopy areturns a copy ofa, that is, a fresh floatarray containing the same elements asa. not the same object, bestie β a fresh one. πval fill : t -> int -> int -> float -> unitβfill a pos len xmodifies the floatarrayain place, storingxin elements numberpostopos + len - 1. RaisesInvalid_argumentifposandlendo not designate a valid subarray ofa. π¨val blit : t -> int -> t -> int -> int -> unitβblit src src_pos dst dst_pos lencopieslenelements from floatarraysrc, starting at element numbersrc_pos, to floatarraydst, starting at element numberdst_pos. it works correctly even ifsrcanddstare the same floatarray, and the source and destination chunks overlap. overlap? handled. slay. β¨ RaisesInvalid_argumentifsrc_posandlendo not designate a valid subarray ofsrc, or ifdst_posandlendo not designate a valid subarray ofdst. πval to_list : t -> float listβto_list areturns the list of all the elements ofa. πval of_list : float list -> tβof_list lreturns a fresh floatarray containing the elements ofl. RaisesInvalid_argumentif the length oflis greater thanSys.max_floatarray_length. π
π Comparison π
val equal : (float -> float -> bool) -> t -> t -> boolβequal eq a bistrueif and only ifaandbhave the same lengthnand for alliin[ 0 ; n-1 ],eq a.(i) b.(i)istrue. Since5.4πΈval compare : (float -> float -> int) -> t -> t -> intβcompare cmp a bcomparesaandbaccording to the shortlex order, that is, shorter arrays are smaller and equal-sized arrays are compared in lexicographic order usingcmpto compare elements. Since5.4β
π¦ Iterators π¦
val iter : (float -> unit) -> t -> unitβiter f aapplies functionfin turn to all the elements ofa. it is equivalent tof a.(0); f a.(1); ...; f a.(length a - 1); (). yes, including that final(), bestie. πval iteri : (int -> float -> unit) -> t -> unitβ same asFloat.Array.iter, but the function is applied with the index of the element as first argument, and the element itself as second argument. index first, element second. iykyk. π’val map : (float -> float) -> t -> tβmap f aapplies functionfto all the elements ofa, and builds a floatarray with the results returned byf. β¨val map_inplace : (float -> float) -> t -> unitβmap_inplace f aapplies functionfto all elements ofa, and updates their values in place. Since5.1πval mapi : (int -> float -> float) -> t -> tβ same asFloat.Array.map, but the function is applied to the index of the element as first argument, and the element itself as second argument. πval mapi_inplace : (int -> float -> float) -> t -> unitβ same asFloat.Array.map_inplace, but the function is applied to the index of the element as first argument, and the element itself as second argument. Since5.1π«Άval fold_left : ('acc -> float -> 'acc) -> 'acc -> t -> 'accβfold_left f init acomputesf (... (f (f init a.(0)) a.(1)) ...) a.(n-1), wherenis the length of the floatarraya. left fold go brrr. π₯val fold_right : (float -> 'acc -> 'acc) -> t -> 'acc -> 'accβfold_right f a initcomputesf a.(0) (f a.(1) ( ... (f a.(n-1) init) ...)), wherenis the length of the floatarraya. right fold, same energy, other direction. π
π Iterators on two arrays π
val iter2 : (float -> float -> unit) -> t -> t -> unitβiter2 f a bapplies functionfto all the elements ofaandb. RaisesInvalid_argumentif the floatarrays are not the same size. matching lengths only, bestie. πval map2 : (float -> float -> float) -> t -> t -> tβmap2 f a bapplies functionfto all the elements ofaandb, and builds a floatarray with the results returned byf:[| f a.(0) b.(0); ...; f a.(length a - 1) b.(length b - 1)|]. RaisesInvalid_argumentif the floatarrays are not the same size. β¨
π Array scanning π
val for_all : (float -> bool) -> t -> boolβfor_all f [|a1; ...; an|]checks if all elements of the floatarray satisfy the predicatef. that is, it returns(f a1) && (f a2) && ... && (f an). all of them, or it's a no from me. βval exists : (float -> bool) -> t -> boolβexists f [|a1; ...; an|]checks if at least one element of the floatarray satisfies the predicatef. that is, it returns(f a1) || (f a2) || ... || (f an). just one is enough to make it true, periodt. π₯val mem : float -> t -> boolβmem a setistrueif and only if there is an element ofsetthat is structurally equal toa, i.e. there is anxinsetsuch thatcompare a x = 0. structural equality check, not IEEE. π§val mem_ieee : float -> t -> boolβ same asFloat.Array.mem, but uses IEEE equality instead of structural equality. important distinction, bestie. β‘
π Array searching π
val find_opt : (float -> bool) -> t -> float optionβ signature only in the original, so here it is exactly, no invented extras. π«Άval find_index : (float -> bool) -> t -> int optionβfind_index f areturnsSome i, whereiis the index of the first element of the arrayathat satisfiesf x, if there is such an element. it returnsNoneif there is no such element. Since5.1πval find_map : (float -> 'a option) -> t -> 'a optionβ signature only in the original. keeping it raw and exact. β¨val find_mapi : (int -> float -> 'a option) -> t -> 'a optionβ same asfind_map, but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument. Since5.1π
π Sorting and shuffling π
val sort : (float -> float -> int) -> t -> unitβ sort a floatarray in increasing order according to a comparison function. the comparison function must return0if its arguments compare as equal, a positive integer if the first is greater, and a negative integer if the first is smaller (see below for a complete specification). for example,compareis a suitable comparison function. after callingsort, the array is sorted in place in increasing order.sortis guaranteed to run in constant heap space and (at most) logarithmic stack space. β
the current implementation uses Heap Sort. it runs in constant stack space. no cap. π₯
Specification of the comparison function: let a be the floatarray and cmp the comparison function. the following must be true for all x, y, z in a:
cmp x y > 0if and only ifcmp y x < 0- if
cmp x y >= 0andcmp y z >= 0thencmp x z >= 0
when sort returns, a contains the same elements as before, reordered in such a way that for all i and j valid indices of a:
cmp a.(i) a.(j) >= 0ifi >= j
that's the full spec, bestie β don't skip the inequalities. π
val stable_sort : (float -> float -> int) -> t -> unitβ same asFloat.Array.sort, but the sorting algorithm is stable (i.e. elements that compare equal are kept in their original order) and not guaranteed to run in constant heap space. the current implementation uses Merge Sort. it uses a temporary floatarray of lengthn/2, wherenis the length of the floatarray. it is usually faster than the current implementation ofFloat.Array.sort. stable and speedy? we love to see it. π¦val fast_sort : (float -> float -> int) -> t -> unitβ same asFloat.Array.sortorFloat.Array.stable_sort, whichever is faster on typical input. it's giving "pick the faster one" energy. β‘val shuffle : rand:(int -> int) -> t -> unitβshuffle rand arandomly permutesa's elements usingrandfor randomness. the distribution of permutations is uniform.randmust be such that a call torand nreturns a uniformly distributed random number in the range[ 0 ; n-1 ].Random.intcan be used for this (do not forget toRandom.self_initthe generator). Since5.2π²
π Float arrays and Sequences π
val to_seq : t -> float Seq.tβ signature only in the original, kept exactly as-is. π«Ά
Iterate on the floatarray, in increasing order. Modifications of the floatarray during iteration will be reflected in the sequence. β¨
val to_seqi : t -> (int * float) Seq.tβ iterate on the floatarray, in increasing order, yielding indices along elements. Modifications of the floatarray during iteration will be reflected in the sequence. π¦val of_seq : float Seq.t -> tβ create an array from the generator. πval map_to_array : (float -> 'a) -> t -> 'a arrayβmap_to_array f aapplies functionfto all the elements ofa, and builds an array with the results returned byf:[| f a.(0); f a.(1); ...; f a.(length a - 1) |]. πval map_from_array : ('a -> float) -> 'a array -> tβmap_from_array f aapplies functionfto all the elements ofa, and builds a floatarray with the results returned byf. πΈ
π Arrays and concurrency safety π
Care must be taken when concurrently accessing float arrays from multiple domains: accessing an array will never crash a program, but unsynchronized accesses might yield surprising (non-sequentially-consistent) results. π
βοΈ Atomicity βοΈ
Every float array operation that accesses more than one array element is not atomic. This includes iteration, scanning, sorting, splitting and combining arrays. π«Ά
For example, consider the following program:
let size = 100_000_000
let a = Float.Array.make size 1.
let update a f () =
Float.Array.iteri (fun i x -> Float.Array.set a i (f x)) a
let d1 = Domain.spawn (update a (fun x -> x +. 1.))
let d2 = Domain.spawn (update a (fun x -> 2. *. x +. 1.))
let () = Domain.join d1; Domain.join d2
After executing this code, each field of the float array a is either 2., 3., 4. or 5.. If atomicity is required, then the user must implement their own synchronization (for example, using Mutex.t). π₯
π₯ Data races π₯
If two domains only access disjoint parts of the array, then the observed behaviour is the equivalent to some sequential interleaving of the operations from the two domains. π§
A data race is said to occur when two domains access the same array element without synchronization and at least one of the accesses is a write. In the absence of data races, the observed behaviour is equivalent to some sequential interleaving of the operations from different domains. π
Whenever possible, data races should be avoided by using synchronization to mediate the accesses to the array elements. β¨
Indeed, in the presence of data races, programs will not crash but the observed behaviour may not be equivalent to any sequential interleaving of operations from different domains. Nevertheless, even in the presence of data races, a read operation will return the value of some prior write to that location with a few exceptions. π
π Tearing π
Float arrays have two supplementary caveats in the presence of data races. π
First, the blit operation might copy an array byte-by-byte. Data races between such a blit operation and another operation might produce surprising values due to tearing: partial writes interleaved with other operations can create float values that would not exist with a sequential execution. π
For instance, at the end of
let zeros = Float.Array.make size 0.
let max_floats = Float.Array.make size Float.max_float
let res = Float.Array.copy zeros
let d1 = Domain.spawn (fun () -> Float.Array.blit zeros 0 res 0 size)
let d2 = Domain.spawn (fun () -> Float.Array.blit max_floats 0 res 0 size)
let () = Domain.join d1; Domain.join d2
the res float array might contain values that are neither 0. nor max_float. π
Second, on 32-bit architectures, getting or setting a field involves two separate memory accesses. In the presence of data races, the user may observe tearing on any operation. β
That's the whole page, bestie! Footer vibes: OCamldoc, 2026-06-22, Float.Array(3) β slay and stay safe out there π
π¦ where this page comes from
- arch rolling: ocaml 5.5.0-1 Β· LGPL2.1 AND custom: QPL-1.0
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms