quantumlib / qsim

Schrödinger and Schrödinger-Feynman simulators for quantum circuits.
Apache License 2.0
455 stars 153 forks source link

`denormals_are_zeros` setting has unexpected side effects #666

Open richrines1 opened 4 months ago

richrines1 commented 4 months ago

qsim updates global flush-to-zero and denormals-are-zero control flags, but never resets them to their original values. This can lead to unexpected changes in the behavior of downstream code, e.g.:

import cirq
import ctypes

from qsimcirq import QSimOptions, QSimSimulator

orig_value = ctypes.c_float(1e-40).value

_ = QSimSimulator(qsim_options=QSimOptions(denormals_are_zeros=False)).simulate(cirq.Circuit())

assert ctypes.c_float(1e-40).value == orig_value  # passes

_ = QSimSimulator(qsim_options=QSimOptions(denormals_are_zeros=True)).simulate(cirq.Circuit())

assert ctypes.c_float(1e-40).value == orig_value  # fails

_ = QSimSimulator().simulate(cirq.Circuit())

assert ctypes.c_float(1e-40).value == orig_value  # passes

it would be nice if these flags were reset after the simulation (ideally even if the simulation itself fails)