Update page 'Day 1 homework - Xuanyi Wang (Sloetjes)'

xuanyi.wang
2023-03-30 20:53:18 +02:00
parent 12bcad3f39
commit b28300db2e
+165
@@ -0,0 +1,165 @@
# Xuanyi Wang\_Day-1\_Homework\_03/30/23
### 1. What is the name of the international standard for floating-point representation?
<span style="color:blue">**IEEE 754**</span>
### 2. How many bits are the floating point numbers defined by that standard allowed to be?
####<span style="color:blue"> Single-precision format (32-bits)</span>
Single-precision format floating-point numbers are represented using 32 bits, with 1 bit for the sign, 8 bits for the exponent, and 23 bits for the significand (mantissa);
####<span style="color:blue"> Double-precision format (64-bits)</span>
Double-precision floating-point numbers are represented using 64 bits, with 1 bit for the sign, 11 bits for the exponent, and 52 bits for the significand.
* The IEEE 754 standard also defines extended-precision and quadruple-precision formats, which use <span style="color:blue">80 bits</span> and <span style="color:blue">128 bits</span>, respectively.
* However, these formats are less commonly used than the single-precision and double-precision formats.</span>
### 3. Does your computer support all those formats? Can you think of an easy way to check with only one line of Python?
```
import platform
platform.architecture()[0]
```
### 4. Why doesn't this code give the same answers to the two multiplications?
```
mport pandas as pd
import numpy as np
# Generate two random 64-bit integers
num1 = np.random.randint(0, 2**63 - 1)
num2 = np.random.randint(0, 2**63 - 1)
# Multiply them together using the normal Python multiplication operator
print(f"num1 * num2 = {num1 * num2}")
# Create a Pandas DataFrame with the generated numbers
data = {'Number1': [num1], 'Number2': [num2]}
df = pd.DataFrame(data)
# Multiply the numbers together using the Pandas multiplication operator
df['Product'] = df['Number1'] * df['Number2']
print(df)
```
#### Answer:
`num1` and `num2` are both 64-bit integers, which means that ` num1 * num2` is performed using 64-bit integer arithmetic. However,`df[‘Number1’] ` and `df[‘Number2’] ` are Pandas Series objects and they are 64-bit floating point numbers so `df[‘Number1’] * df[‘Number2’] ` is performed using floating-point arithmetic which involves approximations and rounding errors.
### 1. You can use sys.getsizeof to see how large a Python object is. Does the size of a Python floating-point number change as it gets larger? Why or why not?
**<span style="color:blue"> The size of a Python floating-point number does not change as it gets larger.**
In Python, floating-point numbers are represented using the IEEE 754 standard, which uses a fixed number of bits to represent the number's value and precision. Specifically, Python uses 64 bits to represent a float.
Regardless of the magnitude of the float, the number of bytes used to represent it remains the same. This is because the IEEE 754 standard uses a fixed number of bits to represent both the exponent and the significand of the floating-point number.
However, it's worth noting that as the magnitude of a floating-point number grows larger, the number of significant digits it can represent decreases. This is due to the limited precision of floating-point arithmetic, and can result in rounding errors when performing calculations with very large or very small floating-point numbers.
### 2. We already know that the precision of floating-point numbers decreases as their magnitude increases. Using Pandas, create a dataframe representing a large amount of US Dollars. What is the smallest number of dollars where adding one cent begins to yield wrong results?
Assuming double-precision floating-point numbers (64 bits), the smallest number of dollars that can be represented is $0.01 divided by 2 to the power of 52 (the number of bits used to represent the fraction part of a double-precision number). This equals approximately **<span style="color:blue">$0.0000000000002384**.
Therefore, any calculation involving adding 0.01 to a dollar amount smaller than **<span style="color:blue">$0.0000000000002384** may yield wrong results due to the limited precision of floating-point arithmetic.
### 3. Name three practical differences between Python strings and bytes. Using sys.getsizeof, see how the sizes may be different. Do emoji change this answer?
**<span style="color:blue"> Encoding**: Python strings are used to represent text data, while bytes are used to represent binary data. Strings are typically encoded using a character encoding such as UTF-8 or ASCII, which maps each character to a sequence of bytes, while bytes represent raw binary data that may not necessarily correspond to any particular character encoding.
**<span style="color:blue"> Immutability**: Python strings are immutable, meaning that once a string is created, its contents cannot be changed. In contrast, bytes are mutable, meaning that their contents can be changed after they are created.
**<span style="color:blue"> Representation**: Python strings are represented using the str type, while bytes are represented using the bytes type. Strings are typically enclosed in quotes (' or ") and can contain any Unicode character, while bytes are enclosed in b quotes and can contain any binary data.
```
import sys
s = "hello world"
b = b"hello world"
print("Size of string:", sys), size.getsizeof(s))
print("Size of bytes:", sys), size.getsizeof(b))
```
###### Output:
```
Size of s1: 60
Size of s2: 44
```
### Emoji Case:
```
s1 = "😊"
s2 = "👩‍👩‍👧‍👧"
print("Size of s1:", sys.getsizeof(s1))
print("Size of s2:", sys.getsizeof(s2))
```
###### Output:
```
Size of s1: 80
Size of s2: 104
```
### 4. Given this sample CSV file (tomato_sales.csv):
```
Store,Region,Tomato_Sales
Store1,East,300
Store2,West,450
tore3,North,500
Store4,South,350
Store5,East,400
```
and this Python file to do a simple accounting function:
```
def read_tomato_sales(file_name):
data = pd.read_csv(file_name)
total_sales = data["Tomato_Sales"].sum() # This will raise an error
print(f"Total tomato sales: {total_sales}")
read_tomato_sales("tomato_sales_error.csv")
```
describe a hypothetical situation where modifying the CSV file to create a type confusion error could cause nuclear war due to AIs taking over the food supply chain.
####Answer:
**<span style="color:blue">Type confusion error** is a type of software vulnerability that occurs when a program assumes a variable is of a certain data type, but it is actually of a different data type. This can lead to unexpected behavior and even security vulnerabilities in some cases. For example, if a program assumes that a user input is an integer, but it is actually a string, the program may crash or produce incorrect results.
A hypothetical situation where modifying the CSV file would create a type confusion error is that if the initial information that has been written into the CSV is modified through **<span style="color:blue">string slicing**, for example, “Store4South350” sliced into “Store3, South, 350”. Though “350” looks like a numeric input, it remains a string. And this kind of input would cause type error in the read\_tomato\_sales().
#### 1. Prevent that nuclear war by modifying read_tomato_sales to perform better data validation.
```
def read_tomato_sales(file_name):
data = pd.read_csv(file_name)
total_sales = data["Tomato_Sales"].astype(int).sum()
print(f"Total tomato sales: {total_sales}")
read_tomato_sales("tomato_sales_error.csv")
```
#### 2. Given today's conversation about character encodings, describe why you would want to use bytes instead of strings when processing data containing multiple human languages at the same time. Write a small Python function to demonstrate this.
When processing data containing multiple human languages at the same time, it's often better to use bytes instead of strings. The reason for this is that **<span style="color:blue">bytes represent the raw data in its original form, while strings represent a specific encoding of the data.** When working with multiple languages, it's possible that the data may contain characters that are not supported by the encoding used by the string. **<span style="color:blue">This can result in data loss or incorrect character conversion.**
Using bytes instead of strings allows us to **<span style="color:blue">preserve the original data and avoid these conversion issues.** Bytes can be processed and encoded using specific character encodings only when necessary, and this can be done explicitly in a controlled way.
By using bytes instead of strings, we can **<span style="color:blue">handle text in multiple languages without worrying about character encoding issues.** We can then decode the bytes using the appropriate encoding when necessary to display or process the text in a specific language.