adding two fixed point numbers
4 views (last 30 days)
Show older comments
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.
0 Comments
Answers (1)
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
See Also
Categories
Find more on Fixed-Point Designer in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!