Type computation: numerical type with twice more bits

I’m trying to write a generic function accepting two Integers as arguments. The function will need a local variable storing the product of the two integers. So if the functions arguments are of type Int16, the local variable needs to be of type Int32, and if the argumetns are of type Int32, then the local variables needs to be of type Int64. I don’t want BigInt, for efficiency reasons. Is there some function like larger_type, behaving like larger_type(Int16) = Int32, larger_type(Int32) = Int64, etc.?

In most cases widen should do what you want.

2 Likes

Adding to @DNF’s suggestion, your problem brings to mind the example in the manual of outer-only constructors, which gives an example use of widen to achieve a similar goal.

Then note on this advice:

I checked and it does widen up to Int128, but then to BigInt, and Float64 to BigFloat. Inherently there’s nothing wrong with going to Int256 or higher (or even just to Int64 before BigInt), it’s just that Julia doesn’t have those types, but a package does up to Int1024 if I recall.

It’s

defined so that arithmetic operations + and - are guaranteed not to overflow nor lose precision for any combination of values that type x can hold.

actually you only need to widen by 1 bit for that, if you had such a type. For a * b you need a-plus-b-number-of-bits, or double them when same type, what widen does. ^ and << are problematic operators.

That’s the short summary of my longer (not, yet, implemented proposal):