# 1.1 The First Programming Encounter: a Formula

## 1.1.1 Using a Program as a Calculator


```python
print(5*0.6 - 0.5*9.81*0.6**2)
```

    1.2342


## 1.1.5 Warning About Typing Program Text


```python
%%capture

# Code (illegal):
"""
write 5*0.6 - 0.5*9.81*0.6^2
"""

# Result:
"""
File "<ipython-input-3-a4896c6d3f86>", line 1
    write 5*0.6 - 0.5*9.81*0.6^2
          ^
SyntaxError: invalid syntax
"""
```

## 1.1.7 Using Variables


```python
v0 = 5
g = 9.81
t = 0.6
y = v0*t - 0.5*g*t**2
print(y)
```

    1.2342


## 1.1.8 Names of Variables


```python
initial_velocity = 5
acceleration_of_gravity = 9.81
TIME = 0.6
VerticalPositionOfBall = initial_velocity*TIME - \
                         0.5*acceleration_of_gravity*TIME**2
print(VerticalPositionOfBall)
```

    1.2342


## 1.1.10 Comments


```python
# Program for computing the height of a ball in vertical motion.
v0 = 5   # initial velocity
g = 9.81 # acceleration of gravity
t = 0.6  # time
y = v0*t - 0.5*g*t**2  # vertical position
print(y)
```

    1.2342



```python
# -*- coding: ASCII -*-
# halløchen
```

scheint trotzdem zu klappen... sonst:


```python
# -*- coding: utf-8 -*-
```

## 1.1.11 Formatting Text and Numbers


```python
print('At t=%g s, the height of the ball is %.2f m.' % (t, y))
```

    At t=0.6 s, the height of the ball is 1.23 m.


*Format string syntax*:


```python
print("At t={t:g} s, the height of the ball is {y:.2f} m.".format(t=t, y=y))
```

    At t=0.6 s, the height of the ball is 1.23 m.



```python
print("""
At t={t:f} s, a ball with
initial velocity v0={v0:.3E} m/s
is located at the height {y:.2f} m.
""".format(t=t, v0=v0, y=y))
```

    
    At t=0.600000 s, a ball with
    initial velocity v0=5.000E+00 m/s
    is located at the height 1.23 m.
    



```python
# Meiner Meinung nach eine schönere Alternative
x = 1234567890
print(f"x = {x:g}")
```

    x = 1.23457e+09


# 1.2 Computer Science Glossary


```python
v0 = 3; g = 9.81; t = 0.6
y = v0*t - 0.5*g*t**2
print(y)
```

    0.034199999999999786



```python
# mathematically false, but in programming just an assignment:
y = y + 3
```


```python
y = 3
print(y)
y = y + 4
print(y)
y = y*y
print(y)
```

    3
    7
    49



```python
v0=3;g=9.81;t=0.6;y=v0*t-0.5*g*t**2;print(y)
```

    0.034199999999999786


# 1.3 Another Formula: Celsius-Fahrenheit Conversion

## 1.3.1 Potential Error: Integer Division


```python
C = 21
F = (9//5)*C + 32
print(F)
# or:
print(9//5*C + 32)

# adjusted for python 3: now // remains floor (integer) division, and / is always float division
# floor division (a//b) calculates the largest integer c so that c*b <= a ("how many times does b fit into a")
```

    53
    53


## 1.3.3 Avoiding Integer Division


```python
from __future__ import division
print(9/5*C + 32)
# wow it works!
```

    69.80000000000001



```python
print(float(2))
```

    2.0


# 1.4 Evaluating Standard Mathematical Functions

## 1.4.1 Example: Using the Square Root Function


```python
v0 = 5
g = 9.81
yc = 0.2
import math
t1 = (v0 - math.sqrt(v0**2 - 2*g*yc))/g
t2 = (v0 + math.sqrt(v0**2 - 2*g*yc))/g
print("At t=%g s and %g s, the height is %g m." % (t1, t2, yc))
```

    At t=0.0417064 s and 0.977662 s, the height is 0.2 m.



```python
import math as m
# m is now the name of the math module
v = m.sin(m.pi)
from math import log as ln
v = ln(5)
from math import sin as s, cos as c, log as ln
x = 1234
v = s(x)*c(x) + ln(x)
print(v)
```

    6.637346500400129



```python
import math
m = math
ln = m.log
s = m.sin
c = m.cos
v = s(x)*c(x) + ln(x)
print(v)
```

    6.637346500400129


## 1.4.2 Example: Computing with $\text{sinh}(x)$


```python
from math import sinh, exp, e, pi
x = 2*pi
r1 = sinh(x)
r2 = 0.5*(exp(x) - exp(-x))
r3 = 0.5*(e**x - e**(-x))
print(r1, r2, r3)
```

    267.74489404101644 267.74489404101644 267.7448940410163


## 1.4.3 A First Glimpse of Rounding Errors


```python
print("%.16f %.16f %.16f" % (r1,r2,r3))
```

    267.7448940410164369 267.7448940410164369 267.7448940410163232


# 1.5 Interactive Computing    

## 1.5.2 Type Conversion


```python
X = 123.9999
print(X, type(X))
X = int(X)
print(X, type(X))
# Decimals are truncated
```

    123.9999 <class 'float'>
    123 <class 'int'>


## 1.5.3 IPython


```python
a = 21
a
```




    21




```python
_ / 7
```




    3.0




```python
__ + 4
```




    25




```python
# !command für system-befehle. (in der ipython-konsole) like:
# !fortune
# !date
# !ls
```

# 1.6 Complex Numbers

## 1.6.1 Complex Arithmetics in Python


```python
u = 2.5 + 3j
u
```




    (2.5+3j)




```python
%%capture

# Code (illegal):
"""
u = 2.5 + j3
"""

# Result:
"""
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-31-a2fc771f4bd2> in <module>()
----> 1 u = 2.5 + j3
      2 u

NameError: name 'j3' is not defined
"""
```


```python
v = 2
u * v
```




    (5+6j)




```python
u**-6/7
```




    (2.0846166182505192e-05+3.446647537619421e-05j)




```python
a = 2; b = 3
c = complex(a, b)
c
```




    (2+3j)




```python
print(f"Re(c) = {c.real}, Im(c) = {c.imag}, c* = {c.conjugate()}")
```

    Re(c) = 2.0, Im(c) = 3.0, c* = (2-3j)


## 1.6.2 Complex Functions in Python


```python
%%capture

# Code (illegal):
"""
from math import sin
r = sin(c)
"""

# Result:
"""
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-51-771d0302db05> in <module>()
      1 from math import sin
----> 2 r = sin(c)

TypeError: can't convert complex to float
"""
```


```python
# Korrekte implementierung mit cmath:
from cmath import sin, exp, pi
print(f"{sin(c):g}")
print(f"{exp(pi*1j):.4f}")
```

    9.1545-4.16891j
    -1.0000+0.0000j


## 1.6.3 Unified Treatment of Complex and Real Functions

Für Berechnungen, wo komlexe und reelle Zahlen gemischt vorkommen, kann man eine andere Library benutzen:


```python
from numpy.lib.scimath import sqrt # bzw. from numpy.lib.scimath import * für alle funktionen.

# Die gleichen Funktionen die hier enthalten sind, sind auch in scipy und scitools.std enthalten:
# from scipy import *
# from scitools.std import *
```

### `math` (float)


```python
from math import sqrt

sqrt(4)    # float
```




    2.0




```python
%%capture

# Code (illegal):
"""
sqrt(-1)
"""

# Result: 
"""
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-79-75be91ddb76a> in <module>()
----> 1 sqrt(-1)

ValueError: math domain error
"""
```

### `cmath` (complex)


```python
from cmath import sqrt

print(sqrt(4))     # complex
print(sqrt(-1))    # complex
```

    (2+0j)
    1j


### `numpy.lib.scimath` (mixed)


```python
from numpy.lib.scimath import sqrt


print(sqrt(4))     # float
print(sqrt(-1))    # complex
```

    2.0
    1j


Roots of a quadratic funtion:


```python
a = 1; b = 2; c = 100    # polynomial coefficients
from numpy.lib.scimath import sqrt
r1 = (-b + sqrt(b**2 - 4*a*c))/(2*a)
r2 = (-b - sqrt(b**2 - 4*a*c))/(2*a)
print(r1, r2)
```

    (-1+9.94987437107j) (-1-9.94987437107j)



```python
c = -20    # updated coefficient
r1 = (-b + sqrt(b**2 - 4*a*c))/(2*a)
r2 = (-b - sqrt(b**2 - 4*a*c))/(2*a)
print(r1, r2)
```

    3.58257569496 -5.58257569496


# 1.7 Symbolic Computing

## 1.7.1 Basic Differentiation and Integration


```python
from sympy import (
    symbols,      # define symbols for symbolic math
    diff,         # differentiate expressions
    integrate,    # integrate expressions
    Rational,     # define rational numbers
    lambdify,     # turn symbolic expr. into Python functions
    )

t, v0, g = symbols('t v0 g')
y = v0*t - Rational(1,2)*g*t**2
dydt = diff(y, t)
dydt
```




    -g*t + v0




```python
print("acceleration:", diff(y, t, t))
```

    acceleration: -g



```python
y2 = integrate(dydt, t)
y2
```




    -g*t**2/2 + t*v0




```python
# lambdify:
v = lambdify((t, v0, g),       # arguments in v
             dydt,             # symbolic expression
             dummify=False)    # damit argumente genannt werden dürfen, ohne dies geht nur v(a,b,c) nicht v(t=a,v0=b,g=c)

v(t = 0, v0 = 5, g = 9.81)
```




    5.0



## 1.7.2 Equation Solving


```python
# solve(e, x): solve expression e to x (for e = 0)
from sympy import solve
roots = solve(y, t)
roots
```




    [0, 2*v0/g]




```python
# inserting values with subs:
y1 = y.subs(t, roots[0])
y2 = y.subs(t, roots[1])
print(y1, y2)
```

    0 0


## 1.7.3 Taylor Series and More


```python
from sympy import exp, sin, cos

# taylor series of e^t of order 3 around t=0
f = exp(t)
f.series(t, 0, 3)
```




    1 + t + t**2/2 + O(t**3)




```python
# latex encoding
from sympy import latex
print(latex(f.series(t, 0, 7)))
```

    1 + t + \frac{t^{2}}{2} + \frac{t^{3}}{6} + \frac{t^{4}}{24} + \frac{t^{5}}{120} + \frac{t^{6}}{720} + \mathcal{O}\left(t^{7}\right)


Result:
$$1 + t + \frac{t^{2}}{2} + \frac{t^{3}}{6} + \frac{t^{4}}{24} + \frac{t^{5}}{120} + \frac{t^{6}}{720} + \mathcal{O}\left(t^{7}\right)$$


```python
# expanding and simplifying expressions

from sympy import symbols, sin, cos, simplify, expand
x, y = symbols('x y')
f = -sin(x)*sin(y) + cos(x)*cos(y)
print(simplify(f))
print(expand(sin(x+y), trig=True)) # requires a trigonometric hint
```

    cos(x + y)
    sin(x)*cos(y) + sin(y)*cos(x)


 # 1.8 Summary

## 1.8.2 : Example: Trajectory of a Ball

### Solution: Onno Eberhard


```python
from sympy import Symbol, lambdify, tan, cos, pi

# Symbols and constants
x = Symbol('x')            # horizontal coordinate [m]
v0 = Symbol('v0')          # initial velocity [km / h]
theta = Symbol('theta')    # angle to x-axis of initial velocity [degrees]
y0 = Symbol('y0')          # initial height [m]
g = 9.81                   # acceleration of gravity [m / s^2]

# Unit conversions
theta = theta * pi / 180    # theta: [degrees] -> [rad]
v0 = v0 * 1000 / 60 / 60    # v0: [km / h] -> [m / s]

# The formula
y = x*tan(theta) - (g * x**2)/(2 * v0**2 * cos(theta)**2) + y0
f = lambdify('x, v0, theta, y0', y, dummify = False)

# Result
y1 = f(x = 0.5, v0 = 15, theta = 60, y0 = 1)
print(f"y1 = {y1:g} m")
```

    y1 = 1.5835 m


### Solution: Book


```python
g = 9.81    # m/s**2
v0 = 15     # km/h
theta = 60  # degrees
x = 0.5     # m
y0 = 1      # m

print("""\
v0    = %.1f km/h
theta = %d degrees 
y0    = %.1f m
x     = %.1f m\
""" % (v0, theta, y0, x))

from math import pi, tan, cos
# Convert v0 to m/s and theta to radians
v0 = v0/3.6
theta = theta*pi/180

y = x*tan(theta) - 1/(2*v0**2)*g*x**2/((cos(theta))**2) + y0

print('y     = %.1f m' % y)
```

    v0    = 15.0 km/h
    theta = 60 degrees 
    y0    = 1.0 m
    x     = 0.5 m
    y     = 1.6 m


7cdb3e93a6a73d985c2e9a35e24a42e325f19565
ipynb
Jupyter Notebook
Chapter 1 - Computing with Formulas.ipynb
onnoeberhard/scipro-primer-notebooks
e9cf1069d62f8c50549d9912403c640f08a99392
MIT
2019-04-18T13:35:42.000Z
2021-09-05T21:01:06.000Z
Chapter 1 - Computing with Formulas.ipynb
onnoeberhard/scipro-primer-notebooks
e9cf1069d62f8c50549d9912403c640f08a99392
MIT
2021-02-15T16:26:00.000Z
2021-02-15T16:26:00.000Z
Chapter 1 - Computing with Formulas.ipynb
onnoeberhard/scipro-primer-notebooks
e9cf1069d62f8c50549d9912403c640f08a99392
MIT
2018-09-30T07:35:00.000Z
2021-08-28T19:15:09.000Z
Qwen/Qwen-72B
1. YES
2. YES