32-bit floating point math in 64-bit Python [duplicate] 32-bit floating point math in 64-bit Python [duplicate] python-3.x python-3.x

32-bit floating point math in 64-bit Python [duplicate]


Extending Yann Vernier's idea, this would be a possible transformer that injects a numpy import and wraps every float literal in numpy.float32.

import astclass Float32Visitor(ast.NodeTransformer):    def visit_Module(self, node):        # add numpy import        imp = ast.Import([ast.alias("numpy")])        node.body = [imp] + node.body        return node    def visit_Num(self, node):        if not isinstance(node.n, float):            return node        return ast.Call(            func=ast.Attribute(                value=ast.Name(id="numpy", ctx=ast.Load()),                attr="float32", ctx=ast.Load()            ),            args=[node],            keywords=[],            starargs=None,            kwargs=None        )

Hooking this into compile is a bit tricky and hackish, however. To do it for a single piece of code, you'd do something like this:

import astparsed = ast.parse(my_code, "my_code.py", mode="exec")parsed = Float32Visitor().visit(parsed)code = compile(parsed, "my_code.py", mode="exec")my_code = eval(code)


The straightforward way is essentially to run a Python built for an environment matching your target, i.e. build it for the target and run it in an emulator on your desktop hardware. Be sure to build it with the appropriate floating point type as the compiler will have software support for wider types. It will be very inefficient but as accurate as your emulator.

If you can make do with just storage behaviour, you can use numpy.float32 or ctypes.c_float, but neither will get you the direct behaviour of mapping floating point literals to that type, and they will likely use 64 or 80 bit operations, which can lead to the rounding differences you want to avoid. The literal remapping is something you could do at an AST level if you wrap your own REPL; while Python has some library assistance for this in the code and ast modules, it's a fairly complex subject.