Double-int32 multiplication gives int32 result type

4 次查看(过去 30 天)
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 个评论
John D'Errico
John D'Errico 2022-2-1
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 2022-2-1
编辑:James Tursa 2022-2-1
@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.

请先登录,再进行评论。

回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

产品


版本

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by