The issue you're experiencing is likely due to a memory-related problem when converting the large floating-point numbers to bytes. Let me explain the problem and provide a solution:
Problem Analysis:
- You're generating very large numbers (around 1e9) by multiplying fractional parts by 2³²
- When you try to convert these to bytes with
bytes(int(n)), Python needs to allocate memory for a bytes object of that size
- For example,
bytes(int(1.77903370e+09)) would try to create a bytes object of about 1.78 GB, which is likely causing your system to kill the process
Solution:
You probably want to convert these numbers to 4-byte representations (32-bit integers) rather than creating massive bytes objects. Here's the corrected code:
import numpy as np
import struct
def printbinl(l):
print([hex(n) for n in l])
hlist = [2, 3, 5, 7, 11, 13, 17, 19]
hlist = np.sqrt(hlist)
hlist = hlist - np.floor(hlist)
hlist *= 2**32
hlist = np.floor(hlist).astype(np.uint32) # Convert to 32-bit unsigned integers
print(hlist)
# Convert each number to 4 bytes (little-endian)
hlist_bytes = [struct.pack('<I', int(n)) for n in hlist]
print(hlist_bytes)
# If you want to see the integer values of each byte
hlist_ints = [list(b) for b in hlist_bytes]
print(hlist_ints)
printbinl([int(n) for n in hlist]) # Print the original 32-bit integers
Key Changes:
- Used
astype(np.uint32) to ensure we're working with 32-bit numbers
- Used
struct.pack to properly convert the numbers to 4-byte sequences
- Added an intermediate step to show the byte values as integers
Alternative Approach:
If you're trying to create a hash function or something similar, you might want to consider this more efficient approach:
import numpy as np
hlist = np.array([2, 3, 5, 7, 11, 13, 17, 19], dtype=np.float64)
hlist = np.sqrt(hlist)
hlist = hlist - np.floor(hlist)
hlist = (hlist * 2**32).astype(np.uint32)
print("32-bit integers:", hlist)
print("Hex values:", [hex(n) for n in hlist])
This avoids the problematic bytes conversion while still giving you the 32-bit integer results you probably want.