Clear Filters
Clear Filters

Double-int32 multiplication gives int32 result type

4 views (last 30 days)
While worknig on some devs, I was getting the error:
"Error using .^
Integers can only be raised to positive integral powers."
Then, I realised was performing this operation:
b = b * CST; % b is double, CST is int32 --> b becomes int32 after multiplication.
I was then surprised to notice it, since as of almost all other programming languages do promote "smaller" built-in types to "higher" ones is better then doing the inverse operation, avoiding unwanted data loss in the conversion operation (do an explicit cast if really wanted). Like exactly in this case.
Why does MATLAB show this behaviour?
  2 Comments
John D'Errico
John D'Errico on 1 Feb 2022
Why? Because that is the behavior chosen by those who designed the software. That other languages behave differently is because they are different languages. Otherwise there would only be one programming language, and we would all be using APL. ;-)
Is one a better behavior? What you may prefer, others may not.
James Tursa
James Tursa on 1 Feb 2022
Edited: James Tursa on 1 Feb 2022
@Michele Esposito Marzino Also note that integer arithmetic in MATLAB pegs overflow/underflow results at the max/min values for the class. Other languages like C/C++/Java typically use modulo (wraparound) results for integer overflow/underflow.

Sign in to comment.

Answers (0)

Products


Release

R2019b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!