Created
March 30, 2018 16:33
-
-
Save JansenZhao/1b2f3696a3550c43256490a8314158ec to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
import pyquil.api as api | |
import scipy.linalg | |
import struct | |
from grove.alpha.phaseestimation.phase_estimation import phase_estimation | |
def bin_to_float(b, precision='d'): | |
""" Convert binary string to a float. """ | |
bf = int_to_bytes(int(b, 2), precision) | |
return struct.unpack('>'+precision, bf)[0] | |
def int_to_bytes(n, precision): | |
""" Int/long to byte string. """ | |
if precision == 'e': | |
# 2 bytes needed for half precision | |
minlen = 2 | |
elif precision == 'f': | |
# 4 bytes needed for IEEE 754 binary32 | |
minlen = 4 | |
else: | |
# 8 bytes needed for IEEE 754 binary64 | |
minlen = 8 | |
nbits = n.bit_length() + (1 if n < 0 else 0) # plus one for any sign bit | |
nbytes = (nbits+7) // 8 # number of whole bytes | |
b = bytearray() | |
for _ in range(nbytes): | |
b.append(n & 0xff) | |
n >>= 8 | |
if minlen and len(b) < minlen: # zero pad? | |
b.extend([0] * (minlen-len(b))) | |
return bytearray(reversed(b)) # high bytes first | |
def float_to_bin(f, precision='d'): | |
""" Convert a float into a binary string. """ | |
ba = struct.pack('>' + precision, f) | |
s = ''.join('{:08b}'.format(b) for b in ba) | |
return s[:-1].lstrip('0') + s[0] # strip all leading zeros except for last | |
qvm = api.QVMConnection() | |
phase = np.pi/16 | |
Z = np.asarray([[1.0, 0.0], [0.0, -1.0]]) | |
Rz = scipy.linalg.expm(1j*Z*phase) | |
p = phase_estimation(Rz, 16) | |
qvm.run(p, [], 1) | |
# Convert the phase to a 16-bit binary representation | |
binary_representation = float_to_bin(phase, 'e') | |
# Convert it back to 16-bit floating point number | |
half_precision = bin_to_float(binary_representation, 'e') | |
print('The double precision floating point number is', phase) | |
print('The half precision floating point number is', half_precision) | |
print("The wave function is ", qvm.wavefunction(p)) | |
print('The binary representation is', binary_representation) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment