how set and retain the the x87 floating point precision mode

0

Q1: I have following C code:

#include <stdio.h>
#include <fpu_control.h>
#include <stdlib.h>

    fpu_control_t fpu_oldcw, fpu_cw = 0x0000007f;
    
    //get old control word
  
    _FPU_GETCW(fpu_oldcw);
    printf("Current control word is: 0x%.8x\n", fpu_oldcw);    
    
    //set the mode    
    _FPU_SETCW(fpu_cw);

    //check the changed mode
    _FPU_GETCW(fpu_oldcw);
    printf("Modified control word is: 0x%.8x\n", fpu_oldcw);    

The output is as expected:

Current control word is: 0x0000037f
Modified control word is: 0x0000007f

This correctly sets the new floating point precision mode. However once the executable is finished, if I reread the control word from another c program then the mode is "0x0000037f". This means previous changed value "0x0000007f" is not retained. So basically how do we retain the new mode? means once we change it, then mode stays updated until we manually change it back to original or whatever.

Q2: Is there any way i can change and retain the mode directly from python? My current thoughts are if i have getter/setter c programs then I can call that code like below in python:

from subprocess import call

call(["./set_precision"])
or 
call(["./get_precision"])

This will only work if the updated mode is retained between two calls to c executable (which is generated by gcc compiler). Another option I was thinking using ctypes like below

libm = ctypes.CDLL("libm.so.6", ctypes.RTLD_GLOBAL)
old_rmode = libm.fegetround()
print( "old_rmode: ", hex(old_rmode) )

However in this case i found only rounding mode but nothing for precision.

Could you please advise what is the best way to set and retain the precision mode on x87 hardware? Thank you.

python
floating-point
precision
ctypes
x87
asked on Stack Overflow Mar 1, 2021 by User852 • edited Mar 1, 2021 by User852

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0