Shortreal datatype not driving exact value

I’m driving a shortreal number to an interface, but when it comes to the monitor its value changes.

Driven value: 0.8
In monitor: 0.800001

I declare the variable as shortreal in item class and in the interface.
What’s happening with this one?

Actually I tried to look at its value on the waveform and it says that the value is 0.800001

Is there a way to round-off this number to the nearest 2 decimal places?

In reply to Reuben:

Hi Reuben,

I’m not sure why you’re getting a different value (probably would need to see the code to figure that out), but I might be able to help you with the rounding. There’s no rounding function in SV/Verilog, but reals are rounded if you convert them to integers. You could also use $shortrealtobits(), modify the bits, and then $bitstoshortreal() to convert it back again. Or you could call a C function to round through the DPI.

But probably the easiest way to round a shortreal would be to use the $swrite() function to convert it to a rounded string and then convert it back to a shortreal:

module shortreal_round();

shortreal myreal = 3.1415926535897932384626433832795028841971693993751058209749445923078;
shortreal rounded;
string str;

initial begin
  $swrite(str, "%0.4f", myreal);
  rounded = str.atoreal();

  $display("rounded number = %f", rounded);
end


endmodule

The output of this simulation using Questasim is:

# rounded number = 3.141600

Notice the fourth digit gets rounded. Just change the format specifier in the $swrite to “%0.2f” and you can round it to two digits.
Good luck,
-Doug

In reply to Doug Smith:

Hi Doug, thanks for the reply about rounding off.

Anyway, my code is like this:


// In item/packet class
shortreal clk_tolerance = 0.8;

// In driver
sigs.drv.clk_tolerance <= req.clk_tolerance;

// In interface
shortreal clk_tolerance;
modport drv (output clk_tolerance);

Is it because that converting 0.8 decimal digit to binary results to an infinite bit size?

In reply to Reuben:

0.8 doesn’t have an exact representation. You could look at something like IEEE 754 shortreal calculator to see more details and the binary representation of such a value.

When using “real” numbers during computation, it is very important to understand how the inherently finite representations impact the computations. Things like operations involving numbers of very different magnitudes, imprecise representations, “Inf” and “NaN” values, etc. are all part of ensuring reasonable results.