<jupyter_start><jupyter_text>Scientific Computing with Python (Second Edition) Chapter 02*We start by importing all from Numpy. As explained in Chapter 01 the examples are written assuming this import is initially done.*<jupyter_code>from numpy import *<jupyter_output><empty_output><jupyter_text>2.1 Variables<jupyter_code>a = 1

diameter = 3.

height = 5.

cylinder = [diameter, height] # reference to a list
print(a, diameter, height,cylinder)
x = 3 # integer (int)
y = 'sunny' # string (str)
print(type(x), type(y))
a = b = c = 1   # a, b and c get the same value 1
print(a,b,c)
a = 1 
a = a + 1   # a gets the value 2 
a = 3 * a   # a gets the value 6
print(a)
a = 1
a += 1  # same as a = a + 1 
a *= 3  # same as a = 3 * a
print(a)<jupyter_output>6<jupyter_text>2.2 Numeric types 2.2.1 Integers<jupyter_code>6 // 2  # 3  an integer value
7 // 2  # 3
7 / 2   # 3.5  a float value<jupyter_output><empty_output><jupyter_text>2.2.2 Floating point numbers<jupyter_code>a = 3.0
a = 30.0e-1
a = 30.e-1
0.4 - 0.3 # returns 0.10000000000000003
0.4 - 0.3 == 0.1 # returns False
exp(1000.) # inf
a = inf
3 - a   # -inf
3 + a   # inf
a + a # inf
a - a # nan
 a / a # nan
x = nan 
x < 0 # False
x > 0 # False
x == x # False
0 < inf     # True 
inf <= inf  # True
 inf == inf  # True 
-inf < inf  # True 
inf - inf   # nan 
exp(-inf)   # 0 
exp(1 / inf)  # 1<jupyter_output><empty_output><jupyter_text>*Remove in the next cell the comment sign to provoke the error*<jupyter_code>seterr(all = 'raise')
#exp(1000)
import sys 
sys.float_info.epsilon # 2.220446049250313e-16
a = float('1.356')
print(a)
a = pi            # returns 3.141592653589793 
a
a1 = float64(a)   # returns 3.1415926535897931 
a1
a2 = float32(a)   # returns 3.1415927 
a2
a - a1            # returns 0.0 
a - a2            # returns -8.7422780126189537e-08
f32 = finfo(float32) 
f32.precision   # 6 (decimal digits) 
f64 = finfo(float64) 
f64.precision   # 15 (decimal digits) 
f = finfo(float) 
f.precision     # 15 (decimal digits) 
f64.max         # 1.7976931348623157e+308 (largest number) 
f32.max         # 3.4028235e+38 (largest number)<jupyter_output><empty_output><jupyter_text>*Uncomment the next line to get the help text*<jupyter_code># help(finfo)     # Check for more options<jupyter_output><empty_output><jupyter_text>2.2.3 Complex numbers<jupyter_code>z = 5.2j
z
z = 3.5 + 5.2j
z
b = 5.2<jupyter_output><empty_output><jupyter_text>*Uncomment the next line to provoke the NameError*<jupyter_code>#z = bj   # returns a NameError<jupyter_output><empty_output><jupyter_text>*Uncomment the next line to provoke the NameError*<jupyter_code>#z = b*j  # returns a NameError
z = b*1j # is correct
z
z = 3.2 + 5.2j 
z.conjugate() # returns (3.2-5.2j)
z = 1j 
z.real       # 0.0 
z.imag       # 1.0<jupyter_output><empty_output><jupyter_text>*Remove in the next cell the comment sign to provoke the error*<jupyter_code># z.imag = 2   # AttributeError: readonly attribute
z = 1 + 0j 
z == 1     # True<jupyter_output><empty_output><jupyter_text>*Remove in the next cell the comment sign to provoke the error*<jupyter_code># float(z)   # TypeError
from matplotlib.pyplot import *
N = 10
# the following vector contains the Nth roots of unity: 
unity_roots = array([exp(1j*2*pi*k/N) for k in range(N)])
# access all the real or imaginary parts with real or imag:
axes(aspect='equal')
plot(unity_roots.real, unity_roots.imag, 'o')
allclose(unity_roots**N, 1) # True
z = 3.2+5.2j 
(z + z.conjugate()) / 2.   # returns (3.2+0j) 
((z + z.conjugate()) / 2.).real   # returns 3.2 
(z - z.conjugate()) / 2.   # returns 5.2j 
((z - z.conjugate()) / 2.).imag   # returns 5.2 
sqrt(z * z.conjugate())   # returns (6.1057350089894991+0j)<jupyter_output><empty_output><jupyter_text>2.3 Booleans<jupyter_code>a = True 
print(a)
b = 30 > 45   # b gets the value False
print(b)
x= 5
if x > 0:
 print("positive")
else:
 print("nonpositive")<jupyter_output>positive<jupyter_text>2.3.1 Boolean operators<jupyter_code>True and False # False
False or True # True
(30 > 45) or (27 < 30) # True
not True # False
not (3 > 4) # True
a=1; b=2; c=2
a < b < c     # same as: a < b and b < c 
a < b <= c    # same as: a < b and b <= c (less or equal)
a == b == c   # same as: a == b and b == c<jupyter_output><empty_output><jupyter_text>2.3.2 Boolean casting<jupyter_code>bool([])   # False 
bool(0)   # False 
bool(' ')   # True 
bool('')   # False 
bool('hello')   # True 
bool(1.2)   # True 
bool(array([1]))   # True<jupyter_output><empty_output><jupyter_text>*Remove in the next cell the comment sign to provoke the error*<jupyter_code># bool(array([1,2]))   # Exception raised!<jupyter_output><empty_output><jupyter_text>2.3.3 Automatic Boolean casting<jupyter_code>a=10
if a:
   ...
if bool(a): # exactly the same as above
   ...
L=[1,2,3]
if L:
    print("list not empty")
else:
    print("list is empty")
L=[]
if L:
    print("list not empty")
else:
    print("list is empty")
n = 20
if n % 2:      # the modulus operator
    print("n is odd")
else:
    print("n is even")
n = 21
if n % 2:
    print("n is odd")
else:
    print("n is even")<jupyter_output>n is odd<jupyter_text>2.3.4 Return values of and and or<jupyter_code>x = 1; y = 0
x and y
def and_as_function(x,y):
    if not x:
        return x
    else:
        return y
and_as_function(x,y)
x or y
y or x
def or_as_function(x,y):
    if x:
        return x
    else:
        return y
or_as_function(x,y)
del x
True or xformatting
False and x
1 or 'a' # produces 1 
'a' or 1 # produces 'a'<jupyter_output><empty_output><jupyter_text>2.3.5 Boolean and integer<jupyter_code>def print_ispositive(x):
    possibilities = ['nonpositive or zero', 'positive']
    return f"x is {possibilities[x>0]}"

print_ispositive(-10)
isinstance(True, bool)
isinstance(False, bool)
isinstance(True, int)
isinstance(False, int)
True + 13<jupyter_output><empty_output><jupyter_text>2.4 Strings<jupyter_code>name = '<NAME>'
child = "Åsa is <NAME>'s daughter"
book = """Aunt Julia 
       and the Scriptwriter"""
book[-1] # returns 'r' 
book[-12:] # returns 'Scriptwriter'<jupyter_output><empty_output><jupyter_text>*Remove in the next cell the comment sign to provoke the error*<jupyter_code># book[1] = 'a'<jupyter_output><empty_output><jupyter_text>2.4.1 Escape sequences and raw strings<jupyter_code>print('Temperature\t20\tC\nPressure\t5\tPa')
a=""" 
A multi-line 
example""" 
a #  returns '\nA multi-line \nexample'
print(a)
latexfontsize="\\tiny"
print(latexfontsize)  # prints \tiny
latexfs=r"\tiny"   # returns "\tiny"
latexfontsize == latexfs  # returns True
print(r"\"")   # returns  \"
print(r"\\")   # returns  \<jupyter_output>\\<jupyter_text>*Remove in the next cell the comment sign to provoke the error*<jupyter_code># print(r"\")    # returns an error (why?)
r"\"" == '\\"'
r"She: \"I am my dad's girl\"" == 'She: \\"I am my dad\'s girl\\"'<jupyter_output><empty_output><jupyter_text>2.4.2 Operations on strings and string methods<jupyter_code>last_name = 'Carlsson'
first_name = 'Johanna'
full_name = first_name + ' ' + last_name
                              # returns '<NAME>'
full_name    
game = 2 * 'Yo' # returns 'YoYo'
game<jupyter_output><empty_output><jupyter_text>*Remove in the next cell the comment sign to provoke the error*<jupyter_code># game = 2.7 * 'Yo' # returns 'YoYo'
'Anna' > 'Arvi' # returns false 
'ANNA' < 'anna'  # returns true 
'10B' < '11A'    # returns true
text = 'quod erat    demonstrandum'
text.split() # returns ['quod', 'erat', 'demonstrandum']
table = 'Johan;Carlsson;19890327'
table.split(';') # returns ['Johan','Carlsson','19890327']
king = 'CarlXVIGustaf'
king.split('XVI')  # returns ['Carl','Gustaf']<jupyter_output><empty_output><jupyter_text>2.4.3 String formatting<jupyter_code>course_code = "NUMA01"
print("Course code: {}".format(course_code))    # Course code: NUMA01
course_code = "NUMA01"
print(f"Course code: {course_code}")            # Course code: NUMA01
quantity = 33.45
print("{:f}".format(quantity)) # 33.450000
print("{:1.1f}".format(quantity)) # 33.5
print("{:.2e}".format(quantity)) # 3.35e+01
quantity = 33.45
print(f"{quantity:1.1f}")         # 33.5
r"we {} in LaTeX \begin{{equation}}".format('like')<jupyter_output><empty_output><jupyter_text>2.5 Summary*No code*  2.6 Exercises *Code variant 1*<jupyter_code>u = 1.0 # you have to use a float here!
uold = 10. 
for iteration in range(2000):
   if not abs(u-uold) > 1.e-8:
      print('Convergence')
      break # sequence has converged
   uold = u
   u = 2*u
else:
   print('No convergence')<jupyter_output>Convergence<jupyter_text>*Code variant 2*<jupyter_code>u = 1.0 # you have to use a float here!
uold = 10. 
for iteration in range(2000):
   if abs(u-uold) < 1.e-8:
      print('Convergence')
      break # sequence has converged
   uold = u
   u = 2*u
else:
   print('No convergence')<jupyter_output>No convergence
{'fraction_non_alphanumeric': 0.14436141304347827, 'fraction_numerical': 0.05434782608695652, 'mean_word_length': 3.813623978201635, 'pattern_counts': {'":': 0, '<': 122, '<?xml version=': 0, '>': 114, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 1, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '27', 'dir': 'jupyter-structured-clean-dedup', 'id': '403551', 'license': 'MIT', 'n_tokens_mistral': 3836, 'n_tokens_neox': 3487, 'n_words': 934, 'path': 'Chapter02/chapter02.ipynb', 'repo_name': 'mazhengcn/scientific-computing-with-python', 'size': '8858'}