Division for signed ac_fixed could get incorrect result
Closed this issue · 2 comments
zpan007 commented
Below is an example to show the division difference between signed ac_fixed and double:
#include "ac_types/include/ac_fixed.h"
int main()
{
ac_fixed<40,30,true> num = -46800;
ac_fixed<40,30,true> den = 2136;
ac_fixed<40,30,true> q = num / den;
std::cout << "division using ac_fixed division = " << q.to_string(AC_BIN) << ", " << q << std::endl;
q = static_cast<double>(num.to_int64())/den.to_int64();
std::cout << "division using double = " << q.to_string(AC_BIN) << ", " << q << std::endl;
return 0;
}
The output of the above code snippet.
division using ac_fixed = 0b101010.0001011101, -21.9091796875
division using double = 0b101010.0001011100, -21.91015625
andres-takach commented
Good observation. However, as Table 3 in the documentation indicates the
ac_fixed division rounds towards zero. This was done to be consistent with
the integer division (both ac_int and C native integers).
So if you add the following lines to your code:
ac_fixed<40,30,true,*AC_TRN_ZERO*> q3 =
static_cast<double>(num.to_int64())/den.to_int64();
std::cout << "division using double with TRN_ZERO = " <<
q3.to_string(AC_BIN) << ", " << q3 << std::endl;
you will find that the results are as expected:
division using ac_fixed division = 0b101010.0001011101, *-21.9091796875*
division using double = 0b101010.0001011100, -21.91015625
division using double with *TRN_ZERO* = 0b101010.0001011101,
*-21.9091796875 *
Andres Takach
…On Thu, Feb 20, 2020 at 10:20 AM Zhengjun Pan ***@***.***> wrote:
Below is an example to show the division difference between signed
ac_fixed and double:
#include "ac_types/include/ac_fixed.h"
int main()
{
ac_fixed<40,30,true> num = -46800;
ac_fixed<40,30,true> den = 2136;
ac_fixed<40,30,true> q = num / den;
std::cout << "division using ac_fixed division = " << q.to_string(AC_BIN) << ", " << q << std::endl;
q = static_cast<double>(num.to_int64())/den.to_int64();
std::cout << "division using double = " << q.to_string(AC_BIN) << ", " << q << std::endl;
return 0;
}
The output of the above code snippet.
division using ac_fixed = 0b101010.0001011101, -21.9091796875
division using double = 0b101010.0001011100, -21.91015625
—
You are receiving this because you are subscribed to this thread.
Reply to this email directly, view it on GitHub
<#9?email_source=notifications&email_token=AEVVDJDFXKYQPC5DXMYQNF3RD2NSLA5CNFSM4KYQ7VB2YY3PNVWWK3TUL52HS4DFUVEXG43VMWVGG33NNVSW45C7NFSM4IPAW64Q>,
or unsubscribe
<https://github.com/notifications/unsubscribe-auth/AEVVDJEOEZAUB6ZST3TEY3DRD2NSLANCNFSM4KYQ7VBQ>
.
zpan007 commented
Ah, thanks for the documentation details. That explains.