Skip to content

Commit

Permalink
Working on Answers to Exercises appendix
Browse files Browse the repository at this point in the history
  • Loading branch information
jledin committed Mar 27, 2022
1 parent 39ff22c commit 9915c46
Show file tree
Hide file tree
Showing 15 changed files with 94 additions and 59 deletions.
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
__Modern Computer Architecture and Organization Second Edition__, by Jim Ledin. Published by Packt Publishing.
# Chapter 1, Exercise 3

Modify the program of Exercise 2 to implement subtraction of 40-digit decimal values. Perform borrowing as required. Test with 0-0, 1-0, 1000000-1, and 0-1. What is the result for 0-1?
Modify the programs of Exercise 1 and Exercise 2 to implement subtraction of 40-digit decimal values. Perform borrowing as required. Test with 0-0, 1-0, 1000000-1, and 0-1. What is the result for 0-1?

# Answer
See the python file [Ex__3_single_digit_subtractor.py](src/Ex__3_single_digit_subtractor.py) for the single-digit subtractor code.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ def increment_adder(a, b, c):
if b == 0: # If accumulator is 0, increment carry
c = c + 1

return a, b, c;
return a, b, c

# Add two decimal digits passed on the command line.
# The sum is returned as digit2 and the carry is 0 or 1.
Expand All @@ -25,5 +25,4 @@ def add_digits(digit1, digit2):
[digit1, digit2, carry] = increment_adder(
digit1, digit2, carry)

return digit2, carry

return digit2, carry
2 changes: 1 addition & 1 deletion Chapter01/Answers to Exercises/src/Ex__2_40_digit_adder.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ def add_40_digits(str1, str2):
sum = [0]*max_digits
carry = [0]*max_digits
for i in range(max_digits):
(sum[i], carry[i]) = Ex__1_single_digit_adder.\
(sum[i], carry[i]) = Ex__1_single_digit_adder. \
add_digits(num1[i], num2[i])

# Ripple the carry values across the digits
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import unittest
import Ex__2_40_digit_adder

class TestSingleDigitAdder(unittest.TestCase):
class Test40DigitAdder(unittest.TestCase):
def test_1(self):
self.assertEqual(Ex__2_40_digit_adder.add_40_digits(
"0", "0"), "0")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ def subtract_40_digits(str1, str2):
diff = [0]*max_digits
carry = [0]*max_digits
for i in range(max_digits):
(diff[i], carry[i]) = Ex__3_single_digit_subtractor.\
(diff[i], carry[i]) = Ex__3_single_digit_subtractor. \
subtract_digits(num1[i], num2[i])

# Ripple the carry values across the digits
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ def decrement_subtractor(a, b, c):
if a == 9: # If accum reached 9, decrement carry
c = c - 1

return a, b, c;
return a, b, c

# Subtract two decimal digits. The difference is returned as
# digit1 and the carry output is 0 (borrow) or 1 (not borrow).
Expand All @@ -26,5 +26,4 @@ def subtract_digits(digit1, digit2):
[digit1, digit2, carry] = decrement_subtractor(
digit1, digit2, carry)

return digit1, carry

return digit1, carry
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import unittest
import Ex__3_40_digit_subtractor

class TestSingleDigitSubtractor(unittest.TestCase):
class Test40DigitSubtractor(unittest.TestCase):
def test_1(self):
self.assertEqual(Ex__3_40_digit_subtractor.
subtract_40_digits("0", "0"), "0")
Expand Down
4 changes: 2 additions & 2 deletions Chapter06/Answers to Exercises/src/Ex__2_dct_formula.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,14 @@
dct_coef = [[i for i in range(len(x))] for j in range(len(x))]
for n in range(len(x)):
for k in range(len(x)):
dct_coef[n][k] = math.cos((math.pi/len(x))*(n + 1/2)*k);
dct_coef[n][k] = math.cos((math.pi/len(x))*(n + 1/2)*k)

# Compute the DCT
x_dct = [i for i in range(len(x))]
for k in range(len(x)):
x_dct[k] = 0;
for n in range(len(x)):
x_dct[k] += x[n]*dct_coef[n][k];
x_dct[k] += x[n]*dct_coef[n][k]

# Print the results
print('Index', end='')
Expand Down
18 changes: 12 additions & 6 deletions Chapter07/Answers to Exercises/src/Ex__3_row_column_major_order.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@

total_time = t1 - t0
col_major_time = col_major_time + total_time
print(' Column-major time to fill array: %.2f sec' % total_time)
print(' Column-major time to fill array: %.2f sec' %
total_time)

t0 = time.time()
for i in range(dim):
Expand All @@ -40,20 +41,25 @@

total_time = t1 - t0
row_major_time = row_major_time + total_time
print(' Row-major time to fill array: %.2f sec' % total_time)
print(' Row-major time to fill array: %.2f sec' %
total_time)
print('')

row_major_average = row_major_time / num_passes
col_major_average = col_major_time / num_passes

if (row_major_average < col_major_average):
winner = 'row'
pct_better = 100 * (col_major_average - row_major_average) / col_major_average
pct_better = 100 * (col_major_average -
row_major_average) / col_major_average
else:
winner = 'column'
pct_better = 100 * (row_major_average - col_major_average) / row_major_average
pct_better = 100 * (row_major_average -
col_major_average) / row_major_average

print('Average row-major time : %.2f sec' % row_major_average)
print('Average column-major time: %.2f sec' % col_major_average)
print('Average time difference : %.2f sec' % ((row_major_time-col_major_time) / num_passes))
print(('Winner is ' + winner + '-major indexing; It is faster by %.2f%%') % pct_better)
print('Average time difference : %.2f sec' % (
(row_major_time-col_major_time) / num_passes))
print(('Winner is ' + winner +
'-major indexing; It is faster by %.2f%%') % pct_better)
2 changes: 1 addition & 1 deletion Chapter14/Answers to Exercises/Ex__3_install_updates.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,4 @@ Update the operating system and other applications and services (such as Java) o

1. If an application has an option to automatically check for updates, ensure it is turned on. You may want to be notified when updates are available but not have them installed automatically.

1. Set up a repeating reminder in your calendar application to notify you to check for updates for all devices and applications at the shortest interval you believe is reasonable, whether it is weekly, biweekly, or monthly. Don't wait too long between updates because your systems are vulnerable during the period between the identification of the vulnerability and your installation of the update that fixes it.
1. Set up a repeating reminder in your calendar application to notify you to check for updates for all devices and applications at the shortest interval you believe is reasonable, whether it is weekly, biweekly, or monthly. Don't wait too long between updates because your systems are vulnerable during the period between the identification of a vulnerability and your installation of the update that fixes it.
10 changes: 5 additions & 5 deletions Chapter15/Answers to Exercises/Ex__2_setup_full_bitcoin_node.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,12 @@ __Modern Computer Architecture and Organization Second Edition__, by Jim Ledin.
Set up a full bitcoin peer node and connect it to the bitcoin network. Download the bitcoin core software from https://bitcoin.org/en/download. It is best to have a fast internet connection and at least 200 GB of free disk space.

# Answer
Download the bitcoin core installer from https://bitcoin.org/en/download and run it.
1. Download the bitcoin core installer from https://bitcoin.org/en/download and run it.

After installation completes, run the bitcoin core application. The application will begin downloading the entire bitcoin blockchain beginning with the genesis block from 2009 up to the most recently added block. This process will take several hours or days depending on your internet bandwidth.
1. After installation completes, run the bitcoin core application. The application will begin downloading the entire bitcoin blockchain beginning with the genesis block from 2009 up to the most recently added block. This process will take several hours or days depending on your internet bandwidth.

Although bitcoin core will consume about 200 GB of disk space during the initial validation process, it will reduce its storage requirements to a disk space limit you select, which defaults to 2 GB.
1. Although bitcoin core will consume about 200 GB of disk space during the initial validation process, it will reduce its storage requirements to a disk space limit you select, which defaults to 2 GB.

After the blockchain has downloaded, the node will transition into operation as a full network peer. You can display the application's connections to network peers and monitor the addition of freshly created transactions into the pool of transactions awaiting inclusion on a future block to be added to the blockchain.
1. After the blockchain has downloaded, the node will transition into operation as a full network peer. You can display the application's connections to network peers and monitor the addition of freshly created transactions into the pool of transactions awaiting inclusion on a future block to be added to the blockchain.

You can also create a bitcoin wallet within the application and use it to conduct your own bitcoin transactions. If you use this application to store a significant quantity of bitcoin, be certain you are enforcing best security practices for all aspects of the host computer operating system and its applications to ensure you don't get hacked and have your coins stolen.
1. You can also create a bitcoin wallet within the application and use it to conduct your own bitcoin transactions. If you use this application to store a significant quantity of bitcoin, be certain you are enforcing best security practices for all aspects of the host computer operating system and its applications to ensure you don't get hacked and have your coins stolen.
16 changes: 11 additions & 5 deletions Chapter15/Answers to Exercises/src/Ex__1_compute_block_hash.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,15 @@
import hashlib

# The block header copied from bitaps.com
header = '00000020505424e0dc22a7fb1598d3a048a31957315f737ec0d00b' + \
'0000000000000000005f7fbc00ac45edd1f6ca7713f2b048d8a771c95e1' + \
'afd9140d3a147a063f64a76781ea461139a0c17f666fc1afdbc08'
header = '00000020505424e0dc22a7fb1598d3a048a31957315f' + \
'737ec0d00b0000000000000000005f7fbc00ac45edd1f6ca7' + \
'713f2b048d8a771c95e1afd9140d3a147a063f64a76781ea4' + \
'61139a0c17f666fc1afdbc08'

# The hash of the header copied from bitaps.com
header_hash = \
'00000000000000000000bc01913c2e05a5d38d39a9df0c8ba4269abe9777f41f'
'00000000000000000000bc01913c2e05a5d38d39a9df0c8ba' + \
'4269abe9777f41f'

# Cut off any extra bytes beyond the 80-byte header
header = header[:160]
Expand All @@ -31,9 +33,13 @@
computed_hash = computed_hash[::-1]

# Convert the binary header hash to a hexadecimal string
computed_hash = binascii.hexlify(computed_hash).decode("utf-8")
computed_hash = \
binascii.hexlify(computed_hash).decode("utf-8")

# Print the result
print('Header hash: ' + header_hash)
print('Computed hash: ' + computed_hash)

if header_hash == computed_hash:
result = 'Hashes match!'
else:
Expand Down
15 changes: 10 additions & 5 deletions Chapter16/Answers to Exercises/src/Ex__2_load_dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,21 @@
import matplotlib.pyplot as plt

def load_dataset():
(train_images, train_labels), (test_images, test_labels) = datasets.cifar10.load_data()
(train_images, train_labels), \
(test_images, test_labels) = \
datasets.cifar10.load_data()

# Normalize pixel values to the range 0-1
train_images = train_images / 255.0
test_images = test_images / 255.0

return train_images, train_labels, test_images, test_labels
return train_images, train_labels, \
test_images, test_labels

def plot_samples(train_images, train_labels):
class_names = ['Airplane', 'Automobile', 'Bird', 'Cat', 'Deer',
'Dog', 'Frog', 'Horse', 'Ship', 'Truck']
class_names = ['Airplane', 'Automobile', 'Bird',
'Cat', 'Deer','Dog', 'Frog',
'Horse', 'Ship', 'Truck']

plt.figure(figsize=(14,7))
for i in range(60):
Expand All @@ -29,5 +33,6 @@ def plot_samples(train_images, train_labels):
plt.show()

if __name__ == '__main__':
train_images, train_labels, test_images, test_labels = load_dataset()
train_images, train_labels, \
test_images, test_labels = load_dataset()
plot_samples(train_images, train_labels)
26 changes: 17 additions & 9 deletions Chapter16/Answers to Exercises/src/Ex__3_create_network.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,20 @@

"""Ex__3_create_network.py: Answer to Ch 16 Ex 3."""

from tensorflow.keras import datasets, layers, models, optimizers, losses
from tensorflow.keras import datasets, layers, models, \
optimizers, losses

def load_dataset():
(train_images, train_labels), (test_images, test_labels) = datasets.cifar10.load_data()
(train_images, train_labels), \
(test_images, test_labels) = \
datasets.cifar10.load_data()

# Normalize pixel values to the range 0-1
train_images = train_images / 255.0
test_images = test_images / 255.0

return train_images, train_labels, test_images, test_labels
return train_images, train_labels, \
test_images, test_labels

def create_model():
# Each image is 32x32 pixels with 3 RGB color planes
Expand All @@ -34,15 +38,18 @@ def create_model():

model = models.Sequential([
# First convolutional layer followed by max pooling
layers.Conv2D(filters_layer1, conv_filter_size, activation='relu', input_shape=image_shape),
layers.Conv2D(filters_layer1, conv_filter_size,
activation='relu', input_shape=image_shape),
layers.MaxPooling2D(pooling_size),

# Second convolutional layer followed by max pooling
layers.Conv2D(filters_layer2, conv_filter_size, activation='relu'),
layers.Conv2D(filters_layer2, conv_filter_size,
activation='relu'),
layers.MaxPooling2D(pooling_size),

# Third convolutional layer followed by flattening
layers.Conv2D(filters_layer3, conv_filter_size, activation='relu'),
layers.Conv2D(filters_layer3, conv_filter_size,
activation='relu'),
layers.Flatten(),

# Dense layer followed by the output layer
Expand All @@ -51,12 +58,13 @@ def create_model():
])

model.compile(optimizer=optimizers.Adam(),
loss=losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
loss=losses.SparseCategoricalCrossentropy(
from_logits=True), metrics=['accuracy'])

return model

if __name__ == '__main__':
train_images, train_labels, test_images, test_labels = load_dataset()
train_images, train_labels, test_images, \
test_labels = load_dataset()
model = create_model()
model.summary()
42 changes: 27 additions & 15 deletions Chapter16/Answers to Exercises/src/Ex__4_train_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,16 @@
import matplotlib.pyplot as plt

def load_dataset():
(train_images, train_labels), (test_images, test_labels) = datasets.cifar10.load_data()
(train_images, train_labels), \
(test_images, test_labels) = \
datasets.cifar10.load_data()

# Normalize pixel values to the range 0-1
train_images = train_images / 255.0
test_images = test_images / 255.0

return train_images, train_labels, test_images, test_labels
return train_images, train_labels, \
test_images, test_labels

def create_model():
# Each image is 32x32 pixels with 3 RGB color planes
Expand All @@ -35,15 +38,18 @@ def create_model():

model = models.Sequential([
# First convolutional layer followed by max pooling
layers.Conv2D(filters_layer1, conv_filter_size, activation='relu', input_shape=image_shape),
layers.Conv2D(filters_layer1, conv_filter_size,
activation='relu', input_shape=image_shape),
layers.MaxPooling2D(pooling_size),

# Second convolutional layer followed by max pooling
layers.Conv2D(filters_layer2, conv_filter_size, activation='relu'),
layers.Conv2D(filters_layer2, conv_filter_size,
activation='relu'),
layers.MaxPooling2D(pooling_size),

# Third convolutional layer followed by flattening
layers.Conv2D(filters_layer3, conv_filter_size, activation='relu'),
layers.Conv2D(filters_layer3, conv_filter_size,
activation='relu'),
layers.Flatten(),

# Dense layer followed by the output layer
Expand All @@ -52,23 +58,26 @@ def create_model():
])

model.compile(optimizer=optimizers.Adam(),
loss=losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
loss=losses.SparseCategoricalCrossentropy(
from_logits=True), metrics=['accuracy'])

return model

def train_model(train_images, train_labels, test_images, test_labels, model):
history = model.fit(train_images, train_labels, epochs=10,
validation_data=(test_images, test_labels))
def train_model(train_images, train_labels, \
test_images, test_labels, model):
history = model.fit(train_images, train_labels,
epochs=10, validation_data=(test_images, test_labels))

test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)
test_loss, test_acc = model.evaluate(test_images,
test_labels, verbose=2)

return history, test_acc

def plot_model_accuracy(history):
plt.figure()
plt.plot(history.history['accuracy'], label='Accuracy')
plt.plot(history.history['val_accuracy'], label = 'Validation Accuracy')
plt.plot(history.history['val_accuracy'],
label = 'Validation Accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.ylim([0.5, 1])
Expand All @@ -77,11 +86,14 @@ def plot_model_accuracy(history):
plt.show()

if __name__ == '__main__':
train_images, train_labels, test_images, test_labels = load_dataset()
train_images, train_labels, test_images, \
test_labels = load_dataset()
model = create_model()
history, test_acc = train_model(train_images, train_labels, test_images, test_labels, model)
history, test_acc = train_model(train_images, \
train_labels, test_images, test_labels, model)
print()
print('='*31)
print('| Validation accuracy: {:.2f}% |'.format(100*test_acc))
print('| Validation accuracy: {:.2f}% |'.
format(100*test_acc))
print('='*31)
plot_model_accuracy(history)

0 comments on commit 9915c46

Please sign in to comment.