Calculations wrong in appdesigner

5 views (last 30 days)
Martin Jensen
Martin Jensen on 7 Feb 2023
Answered: Steven Lord on 7 Feb 2023
Any ideas whys this calculation fails in an app, that otherwise operates correctly? All variables have correct numbers.
app.mdot_P33 = 1.2
app.mdot_P3 = 2.4
app.T3 = 315
app.mdot_P4 = 1.2
app.T4 = 316
app.T5 = (app.mdot_P33/app.mdot_P3)*app.T3 + (app.mdot_P4/app.mdot_P3)*app.T4; (Result should be 315.5 but is not??)

Answers (2)

Rik
Rik on 7 Feb 2023
app.mdot_P33 = 1.2;
app.mdot_P3 = 2.4;
app.T3 = 315;
app.mdot_P4 = 1.2;
app.T4 = 316;
app.T5 = (app.mdot_P33/app.mdot_P3)*app.T3 + (app.mdot_P4/app.mdot_P3)*app.T4
app = struct with fields:
mdot_P33: 1.2000 mdot_P3: 2.4000 T3: 315 mdot_P4: 1.2000 T4: 316 T5: 315.5000
As you can see, the result is indee 315.5.
There is one small nuance: because Matlab can only use a finite number of bits for each number, some values have to be rounded. That causes problems if you expect exact numbers later on.
Imagine you have a decimal system and room for 3 decimals. I ask you to divide 1 by 3. You reply that is equal to 0.333. Now I ask you to multiply the result by 3, to which you should reply 0.999. That is essentially what is happening here.

Steven Lord
Steven Lord on 7 Feb 2023
Result should be 315.5 but is not??
So what is it if it's not 315.5?
Since you said this is part of an app my guess is that one or more of those quantities are coming from a component of the app and you're getting the value as a string rather than a number.
h1 = uieditfield("numeric", Value=1234)
h2 = uieditfield("text", Value="5678")
If you run this code in MATLAB (the uieditfield function is not supported for running code on MATLAB Answers) note the difference in the Value properties of h1 and h2. The former is a number (a double scalar in this case), the latter is a char vector.
x1 = h1.Value + 1 % 1235
x2 = h2.Value + 1 % [54 55 56 57] or
char(x2) % '6789'

Products


Release

R2022a

Community Treasure Hunt

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

Start Hunting!