Comparing type precision

I’m building a struct that takes a collection of elements, and I want the inner constructor to parameterize the struct by the element type of the collection.

I showed what I’m looking for as the max_precision function in the example struct below. If all elements provided to the inner constructor are of the same type, then I just parameterize System by (the number of elements, and) the common type of the arguments. If all elements provided to the constructor are not of the same type, then I’d like to select the type of highest precision.

using StaticArrays
struct System{N,T<:AbstractFloat}
  arr::SVector{N,T}

  # If all arguments are of the same type...
  function System(el::T...) where T<:AbstractFloat 
    return new{length(el), T}(SVector(el))
  end

  # Otherwise...
  function System(el...)
    float_type = max_precision(typeof.(el))
    new{length(el), float_type}(SVector(float_type.(el)))
  end

end

I actually think this is not possible, because how would a type know how precise it is relative to another type? But my knowledge here is limited, so I figured I’d post the question just in case.

I believe you are looking for type promotion. Take a look here: https://docs.julialang.org/en/v1/manual/conversion-and-promotion/#Promotion

For example:

julia> x = promote(2, 3.1, 5//7, big(2.3))
(2.0, 3.100000000000000088817841970012523233890533447265625, 0.714285714285714285714285714285714285714285714285714285714285714285714285714282, 2.29999999999999982236431605997495353221893310546875)

There is also promote_type for working with types instead of values.

6 Likes