adding two fixed point numbers

4 views (last 30 days)
scc28x
scc28x on 8 Apr 2021
Edited: scc28x on 16 Apr 2021
Hi, this is probably a newbie question using fixed point designer. I am trying to add two fixed point numbers, one of which is extracted partially from another fixed point number. I don't need to do any hardware code generation later on so I only care about the math being correct. Please see below:
a=fi(1,0,3,0);
b=fi(1,0,3,0);
out=a.bin(1:2)+b;
a.bin(1:2)+b causes an error. I suppose that is because a.bin(1:2) is not a fixed point object.
I know the way to do this is to define a new fi object with the proper wordlength and then do the summation:
c=fi(0,0,2,0);
c.bin=a.bin(1:2);
out=c+b
Is there a different way to do this so I don't need to define an intermediate fi object, c?
Thanks you very much.

Answers (1)

Andy Bartlett
Andy Bartlett on 9 Apr 2021
Bin method returns a string
The bin method of a fi object
a=fi(1,0,3,0);
w = a.bin(1:2)
class(w)
returns a string
w =
'00'
ans =
'char'
and cannot be added to another fi object.
fi is both a constructor and a cast operator
When fi is called, it is both a constructor and a run-time cast operation.
Your goal of adding b to the two most significant bits of a without creating an intermediate variable can be achieved using fi as a cast.
wl = 3;
iMax = 2^wl - 1;
nPts = 8;
vA = randi([0 iMax],1,nPts);
vB = randi([0 iMax],1,nPts);
a=fi(vA,0,3,0);
b=fi(vB,0,3,0);
outFi = fi( a, 0, 2, -1, 'RoundMode', 'floor') + b
%
% check math to show that this is correct.
% Luxury doubles math answer and the fixed-point answer should be
% off by 0 or 1 depending on whether bit was dropped from a
%
outDbl = double(a) + double(b);
err = double(outFi) - outDbl;
fi_dbl_err = [
double(outFi)
outDbl
err]
Running this script with this random number generator seed
rng(12345);
produced the following output
outFi =
11 7 5 7 4 4 8 9
numerictype(0,4,0)
RoundingMethod: Floor
OverflowAction: Saturate
ProductMode: FullPrecision
SumMode: FullPrecision
fi_dbl_err =
11 7 5 7 4 4 8 9
12 7 6 8 4 4 9 10
-1 0 -1 -1 0 0 -1 -1
  1 Comment
scc28x
scc28x on 16 Apr 2021
Edited: scc28x on 16 Apr 2021
Thank you for your reply. I still don't quite understand the "cast" feature. Using the idea above. Here is an example:
a=fi(2,0,3,0);
k=fi(a,0,3,1)+1;
In this case, k becomes "3" and k.bin='0110'. Maybe I missed something but this is not achieving my goal. It is merely shifting the decimal location. The underlying value of k is retained at 2.0+1=3.0.
What I want to see is:
a.bin='0010' is bit shifted to left by 1, so we get '0100'.
Now when adding 1 to "a", we get '0101'. In other words, the underlying value actually changes.
I was thinking about using bitsliceget to accomplish this. Is it the best way?
Thanks again.

Sign in to comment.

Products


Release

R2020b

Community Treasure Hunt

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

Start Hunting!