Arithmetic promotion: floating-point to integer?

5 次查看(过去 30 天)
Hi,
[quote "MATLAB - Programming Fundamentals R2011b.pdf"] Arithmetic operations that involve both integers and floating-point always result in an integer data type. MATLAB rounds the result, when necessary, according to the default rounding algorithm. The example below yields an exact answer of 1426.75 which MATLAB then rounds to the next highest integer:
int16(325) * 4.39
ans =
1427
[/quote]
In C/C++, the arithmetic promotion rule is to upper ↑: char to int, int unsigned int, int to float, float to double, etc.
Why Matlab designs to be to lower (int)?
Bob

采纳的回答

Mike Hosea
Mike Hosea 2011-10-13
I don't know. Since I work in code generation, these sorts of behaviors are a regular nuisance to me, but maybe I can imagine why. In MATLAB, most users do almost everything with doubles. When programming in MATLAB language, the average user doesn't even think about numeric types. I wasn't around then, but I think integers were originally added to the language primarily because it was burdensome to represent things like images as large arrays of doubles. Having added integers to the language to save on storage, you wouldn't want something simple like multiplying a large int8 array by 2 (that's double precision 2.0 in MATLAB) to generate a large double precision array out of a large integer array. I guess they preferred the current behavior to requiring, in that case, multiplication by int8(2). This rationale is, of course, less compelling when we're talking about scalars, but having inconsistent rules for scalars would be madness. -- Mike
  12 个评论
Bob Li
Bob Li 2011-10-17
Walter,
Thanks for answer. "My questions" page only shows something like:
2answers
0votes
No rich formatting for posts?
Asked 4 days ago by Bob Li
Accepted Answer from Walter Roberson
Tags fomatting post
But I cannot find any information about which one has last been updated?
Walter Roberson
Walter Roberson 2011-10-17
Your My Questions page should (for you) currently list 7 questions. They are ordered from most recently updated (by anyone, including via comments) to least recently updated. What you list above is just the information for one of the questions: there should be 6 above that one.

请先登录,再进行评论。

更多回答(0 个)

Community Treasure Hunt

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

Start Hunting!

Translated by