# 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.*



```python
from numpy import *
```

## 2.1 Variables


```python
a = 1

diameter = 3.

height = 5.

cylinder = [diameter, height] # reference to a list
```


```python
print(a, diameter, height,cylinder)
```

    1 3.0 5.0 [3.0, 5.0]



```python
x = 3 # integer (int)
y = 'sunny' # string (str)
```


```python
print(type(x), type(y))
```

    <class 'int'> <class 'str'>



```python
a = b = c = 1   # a, b and c get the same value 1
```


```python
print(a,b,c)
```

    1 1 1



```python
a = 1 
a = a + 1   # a gets the value 2 
a = 3 * a   # a gets the value 6
```


```python
print(a)
```

    6



```python
a = 1
a += 1  # same as a = a + 1 
a *= 3  # same as a = 3 * a
```


```python
print(a)
```

    6


### 2.2 Numeric types
#### 2.2.1 Integers


```python
6 // 2  # 3  an integer value
```




    3




```python
7 // 2  # 3
```




    3




```python
7 / 2   # 3.5  a float value
```




    3.5



#### 2.2.2 Floating point numbers


```python
a = 3.0
```


```python
a = 30.0e-1
```


```python
a = 30.e-1
```


```python
0.4 - 0.3 # returns 0.10000000000000003
```




    0.10000000000000003




```python
0.4 - 0.3 == 0.1 # returns False
```




    False




```python
exp(1000.) # inf
```

    /home/claus/anaconda3/lib/python3.7/site-packages/ipykernel_launcher.py:1: RuntimeWarning: overflow encountered in exp
      """Entry point for launching an IPython kernel.





    inf




```python
a = inf
```


```python
3 - a   # -inf
```




    -inf




```python
3 + a   # inf
```




    inf




```python
a + a # inf
```




    inf




```python
a - a # nan
```




    nan




```python
 a / a # nan
```




    nan




```python
x = nan 
x < 0 # False
```




    False




```python
x > 0 # False
```




    False




```python
x == x # False
```




    False




```python
0 < inf     # True 
```




    True




```python
inf <= inf  # True
```




    True




```python
 inf == inf  # True 
```




    True




```python
-inf < inf  # True 
```




    True




```python
inf - inf   # nan 
```




    nan




```python
exp(-inf)   # 0 
```




    0.0




```python
exp(1 / inf)  # 1
```




    1.0



*Remove in the next cell the comment sign to provoke the error*


```python
seterr(all = 'raise')
#exp(1000)
```




    {'divide': 'warn', 'over': 'warn', 'under': 'ignore', 'invalid': 'warn'}




```python
import sys 
sys.float_info.epsilon # 2.220446049250313e-16
```




    2.220446049250313e-16




```python
a = float('1.356')
print(a)
```

    1.356



```python
a = pi            # returns 3.141592653589793 
a
```




    3.141592653589793




```python
a1 = float64(a)   # returns 3.1415926535897931 
a1
```




    3.141592653589793




```python
a2 = float32(a)   # returns 3.1415927 
a2
```




    3.1415927




```python
a - a1            # returns 0.0 
```




    0.0




```python
a - a2            # returns -8.7422780126189537e-08
```




    -8.742278012618954e-08




```python
f32 = finfo(float32) 
f32.precision   # 6 (decimal digits) 
```




    6




```python
f64 = finfo(float64) 
f64.precision   # 15 (decimal digits) 
```




    15




```python
f = finfo(float) 
f.precision     # 15 (decimal digits) 
```




    15




```python
f64.max         # 1.7976931348623157e+308 (largest number) 
```




    1.7976931348623157e+308




```python
f32.max         # 3.4028235e+38 (largest number) 
```




    3.4028235e+38



*Uncomment the next line to get the help text*


```python
# help(finfo)     # Check for more options
```

### 2.2.3 Complex numbers


```python
z = 5.2j
z
```




    5.2j




```python
z = 3.5 + 5.2j
z
```




    (3.5+5.2j)




```python
b = 5.2 
```

*Uncomment the next line to provoke the NameError*


```python
#z = bj   # returns a NameError 
```

*Uncomment the next line to provoke the NameError*


```python
#z = b*j  # returns a NameError
```


```python
z = b*1j # is correct
z
```




    5.2j




```python
z = 3.2 + 5.2j 
z.conjugate() # returns (3.2-5.2j)
```




    (3.2-5.2j)




```python
z = 1j 
z.real       # 0.0 
```




    0.0




```python
z.imag       # 1.0 
```




    1.0



*Remove in the next cell the comment sign to provoke the error*


```python
# z.imag = 2   # AttributeError: readonly attribute
```


```python
z = 1 + 0j 
z == 1     # True 
```




    True



*Remove in the next cell the comment sign to provoke the error*


```python
# float(z)   # TypeError
```


```python
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
```


```python
z = 3.2+5.2j 
(z + z.conjugate()) / 2.   # returns (3.2+0j) 
```




    (3.2+0j)




```python
((z + z.conjugate()) / 2.).real   # returns 3.2 
```




    3.2




```python
(z - z.conjugate()) / 2.   # returns 5.2j 
```




    5.2j




```python
((z - z.conjugate()) / 2.).imag   # returns 5.2 
```




    5.2




```python
sqrt(z * z.conjugate())   # returns (6.1057350089894991+0j)
```




    (6.105735008989499+0j)



## 2.3 Booleans


```python
a = True 
print(a)
b = 30 > 45   # b gets the value False
print(b)
```

    True
    False



```python
x= 5
if x > 0:
 print("positive")
else:
 print("nonpositive")
```

    positive


### 2.3.1 Boolean operators


```python
True and False # False
```




    False




```python
False or True # True
```




    True




```python
(30 > 45) or (27 < 30) # True
```




    True




```python
not True # False
```




    False




```python
not (3 > 4) # True
```




    True




```python
a=1; b=2; c=2
a < b < c     # same as: a < b and b < c 
```




    False




```python
a < b <= c    # same as: a < b and b <= c (less or equal)
```




    True




```python
a == b == c   # same as: a == b and b == c
```




    False



### 2.3.2 Boolean casting


```python
bool([])   # False 
```




    False




```python
bool(0)   # False 
```




    False




```python
bool(' ')   # True 
```




    True




```python
bool('')   # False 
```




    False




```python
bool('hello')   # True 
```




    True




```python
bool(1.2)   # True 
```




    True




```python
bool(array([1]))   # True 
```




    True



*Remove in the next cell the comment sign to provoke the error*


```python
# bool(array([1,2]))   # Exception raised!
```

### 2.3.3 Automatic Boolean casting


```python
a=10
if a:
   ...
if bool(a): # exactly the same as above
   ...
```


```python
L=[1,2,3]
if L:
    print("list not empty")
else:
    print("list is empty")
```

    list not empty



```python
L=[]
if L:
    print("list not empty")
else:
    print("list is empty")
```

    list is empty



```python
n = 20
if n % 2:      # the modulus operator
    print("n is odd")
else:
    print("n is even")
```

    n is even



```python
n = 21
if n % 2:
    print("n is odd")
else:
    print("n is even")
```

    n is odd


### 2.3.4 Return values of and and or


```python
x = 1; y = 0
x and y
```




    0




```python
def and_as_function(x,y):
    if not x:
        return x
    else:
        return y
```


```python
and_as_function(x,y)
```




    0




```python
x or y
```




    1




```python
y or x
```




    1




```python
def or_as_function(x,y):
    if x:
        return x
    else:
        return y
```


```python
or_as_function(x,y)
```




    1




```python
del x
True or xformatting
```




    True




```python
False and x
```




    False




```python
1 or 'a' # produces 1 
```




    1




```python
'a' or 1 # produces 'a'
```




    'a'



### 2.3.5 Boolean and integer


```python
def print_ispositive(x):
    possibilities = ['nonpositive or zero', 'positive']
    return f"x is {possibilities[x>0]}"

print_ispositive(-10)
```




    'x is nonpositive or zero'




```python
isinstance(True, bool)
```




    True




```python
isinstance(False, bool)
```




    True




```python
isinstance(True, int)
```




    True




```python
isinstance(False, int)
```




    True




```python
True + 13
```




    14



## 2.4 Strings


```python
name = 'Johan Carlsson'
```


```python
child = "Åsa is Johan Carlsson's daughter"
```


```python
book = """Aunt Julia 
       and the Scriptwriter"""
```


```python
book[-1] # returns 'r' 
```




    'r'




```python
book[-12:] # returns 'Scriptwriter'
```




    'Scriptwriter'



*Remove in the next cell the comment sign to provoke the error*


```python
# book[1] = 'a' 
```

### 2.4.1 Escape sequences and raw strings


```python
print('Temperature\t20\tC\nPressure\t5\tPa')
```

    Temperature	20	C
    Pressure	5	Pa



```python
a=""" 
A multi-line 
example""" 
a #  returns '\nA multi-line \nexample'
```




    ' \nA multi-line \nexample'




```python
print(a)
```

     
    A multi-line 
    example



```python
latexfontsize="\\tiny"
print(latexfontsize)  # prints \tiny
```

    \tiny



```python
latexfs=r"\tiny"   # returns "\tiny"
latexfontsize == latexfs  # returns True
```




    True




```python
print(r"\"")   # returns  \"
```

    \"



```python
print(r"\\")   # returns  \
```

    \\


*Remove in the next cell the comment sign to provoke the error*


```python
# print(r"\")    # returns an error (why?)
```


```python
r"\"" == '\\"'
```




    True




```python
r"She: \"I am my dad's girl\"" == 'She: \\"I am my dad\'s girl\\"'
```




    True



### 2.4.2 Operations on strings and string methods


```python
last_name = 'Carlsson'
first_name = 'Johanna'
full_name = first_name + ' ' + last_name
                              # returns 'Johanna Carlsson'
full_name    
```




    'Johanna Carlsson'




```python
game = 2 * 'Yo' # returns 'YoYo'
game
```




    'YoYo'



*Remove in the next cell the comment sign to provoke the error*


```python
# game = 2.7 * 'Yo' # returns 'YoYo'
```


```python
'Anna' > 'Arvi' # returns false 
```




    False




```python
'ANNA' < 'anna'  # returns true 
```




    True




```python
'10B' < '11A'    # returns true
```




    True




```python
text = 'quod erat    demonstrandum'
```


```python
text.split() # returns ['quod', 'erat', 'demonstrandum']
```




    ['quod', 'erat', 'demonstrandum']




```python
table = 'Johan;Carlsson;19890327'
table.split(';') # returns ['Johan','Carlsson','19890327']
```




    ['Johan', 'Carlsson', '19890327']




```python
king = 'CarlXVIGustaf'
king.split('XVI')  # returns ['Carl','Gustaf']
```




    ['Carl', 'Gustaf']



### 2.4.3 String formatting


```python
course_code = "NUMA01"
print("Course code: {}".format(course_code))    # Course code: NUMA01
```

    Course code: NUMA01



```python
course_code = "NUMA01"
print(f"Course code: {course_code}")            # Course code: NUMA01
```

    Course code: NUMA01



```python
quantity = 33.45
print("{:f}".format(quantity)) # 33.450000
print("{:1.1f}".format(quantity)) # 33.5
print("{:.2e}".format(quantity)) # 3.35e+01
```

    33.450000
    33.5
    3.35e+01



```python
quantity = 33.45
print(f"{quantity:1.1f}")         # 33.5
```

    33.5



```python
r"we {} in LaTeX \begin{{equation}}".format('like')
```




    'we like in LaTeX \\begin{equation}'



### 2.5 Summary
*No code*

## 2.6 Exercises

*Code variant 1*


```python
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')
```

    Convergence


*Code variant 2*


```python
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')
```

    No convergence


f19962814bb36047c25716f99aa6f8e1f76b0ef5
ipynb
Jupyter Notebook
Chapter02/chapter02.ipynb
mazhengcn/Scientific-Computing-with-Python
1bfcb9f1881f0f025f00cb0d5ce660517386483e
MIT
2021-07-11T11:54:35.000Z
2022-03-24T10:42:58.000Z
Chapter02/chapter02.ipynb
mazhengcn/Scientific-Computing-with-Python
1bfcb9f1881f0f025f00cb0d5ce660517386483e
MIT
Chapter02/chapter02.ipynb
mazhengcn/Scientific-Computing-with-Python
1bfcb9f1881f0f025f00cb0d5ce660517386483e
MIT
2021-04-18T12:51:56.000Z
2022-03-15T16:37:58.000Z
Qwen/Qwen-72B
1. YES
2. YES