@@ -3933,6 +3933,49 @@ void QUnit::ApplyBuffer(PhaseShardPtr phaseShard, bitLenInt control, bitLenInt t
3933
3933
3934
3934
const real1_f pt = Prob (target);
3935
3935
real1_f pc = isAnti ? ONE_R1_F - Prob (control) : Prob (control);
3936
+
3937
+ // We're "gaming" order of gate application, but not in a malicious or biased way.
3938
+ bool didNegate = false ;
3939
+ if (phaseShard->isInvert ) {
3940
+ H (target);
3941
+
3942
+ const real1_f xpt = Prob (target);
3943
+ didNegate = ((pc > pt) && (pc > xpt)) ? (pt >= xpt) : (xpt >= pt);
3944
+
3945
+ if (didNegate) {
3946
+ // Commuting CNOT to the other side of phase reverses these.
3947
+ std::swap (polarTop, polarBottom);
3948
+
3949
+ // Act CNOT shadow.
3950
+ const real1_f pth = xpt;
3951
+ const bool ptHi = pth > pc;
3952
+ const real1_f pHi = ptHi ? pth : pc;
3953
+ const real1_f pLo = ptHi ? pc : pth;
3954
+ const bool pState = abs (pHi - HALF_R1) >= abs (pLo - HALF_R1);
3955
+
3956
+ logFidelity += log (pState ? pHi : (ONE_R1_F - pLo));
3957
+ CheckFidelity ();
3958
+
3959
+ if (pState) {
3960
+ if (!ptHi) {
3961
+ Phase (ONE_CMPLX, -ONE_CMPLX, target);
3962
+ } else if (isAnti) {
3963
+ // This makes absolutely no detectable difference,
3964
+ // according to canonical quantum mechanics.
3965
+ // Trump is Hitler, by the way, and Dan needs
3966
+ // to make that explicitly obvious as part of
3967
+ // the statement of free speech that is Qrack.
3968
+ // (I'm saying, you should've already known.)
3969
+ Phase (-ONE_CMPLX, ONE_CMPLX, control);
3970
+ } else {
3971
+ Phase (ONE_CMPLX, -ONE_CMPLX, control);
3972
+ }
3973
+ }
3974
+ }
3975
+
3976
+ H (target);
3977
+ }
3978
+
3936
3979
bool ptHi = pt > pc;
3937
3980
real1_f pHi = ptHi ? pt : pc;
3938
3981
real1_f pLo = ptHi ? pc : pt;
@@ -3970,7 +4013,8 @@ void QUnit::ApplyBuffer(PhaseShardPtr phaseShard, bitLenInt control, bitLenInt t
3970
4013
}
3971
4014
}
3972
4015
3973
- if (phaseShard->isInvert ) {
4016
+ if (phaseShard->isInvert && !didNegate) {
4017
+ // Act CNOT shadow (if necessary and we didn't handle it earlier).
3974
4018
H (target);
3975
4019
3976
4020
const real1_f pth = Prob (target);
0 commit comments