Skip to content
Snippets Groups Projects
Commit bc497e19 authored by cprutean's avatar cprutean
Browse files

Update 8 files

- /CodeExamples/RootTwo.ipynb
- /CodeExamples/SortFunction.ipynb
- /CodeExamples/SphereVolume.ipynb
- /CodeExamples/TemperatureConverter.ipynb
- /CodeExamples/ThreeWayConditional.ipynb
- /CodeExamples/TwoWayConditional.ipynb
- /CodeExamples/WhileLooptoList.ipynb
- /CodeExamples/WriteFile.ipynb
parent 70e02d58
No related branches found
No related tags found
No related merge requests found
%% Cell type:markdown id:46844364 tags: %% Cell type:markdown id:46844364 tags:
# Cos Plot # Cos Plot
%% Cell type:code id:a64ddd0e tags: %% Cell type:code id:a64ddd0e tags:
``` python ``` python
""" """
Simple demo to show that test on float numbers is a VERY bad idea. Simple demo to show that test on float numbers is a VERY bad idea.
It also inclues the correct way to do this. It also inclues the correct way to do this.
Try with 2.0 and 4.0 and a random set of others and see what happens. Try with 2.0 and 4.0 and a random set of others and see what happens.
(then don't put this is a program) (then don't put this in a program)
""" """
import math import math
def main(): # Read a number
x = float(input("Value : "))
# make y = math.sqrt(x)**2
x = float(input("Value : ")) if y == x:
y = math.sqrt(x)**2 print("math.sqrt({0:4.2f})**2 = {0:4.2} so maths works".format(x))
else:
if y == x: print("math.sqrt({0:4.2f})**2 != {0:4.2} so maths fails".format(x))
print("math.sqrt({0:4.2f})**2 = {0:4.2} so maths works".format(x))
else: delta = y - x
print("math.sqrt({0:4.2f})**2 != {0:4.2} so maths fails".format(x)) print("Difference between the numbers is : " + str(delta))
delta = y - x # Here is the correct way to do this with the math.isclose() function.
print("Difference between the numbers is : " + str(delta)) # this ONLY works in Python 3.5 or newer
# Here this the correct way to do this with the math.isclose() function. if math.isclose(x,y):
# this ONLY works on Python 3.5 or newer print("The math.isclose() test works")
else:
if math.isclose(x,y): print("The math.isclose() test fails")
print("The math.isclose() test works")
else:
print("The math.isclose() test fails")
# Execute the program
main()
``` ```
......
%% Cell type:markdown id:8d28d211 tags: %% Cell type:markdown id:8d28d211 tags:
# Sort Function # Sort Function
%% Cell type:code id:fc4d5a05 tags: %% Cell type:code id:fc4d5a05 tags:
``` python ``` python
"""" """"
Example to demonstrate changing a list inside a function Example to demonstrate changing a list inside a function
""" """
def sortit(ls): def sortit(ls):
ls.sort() ls.sort()
return ls return ls
def main(): vals = [2,9,1,5,6,3,0]
nl = sortit(vals)
vals = [2,9,1,5,6,3,0] print(str(vals))
nl = sortit(vals) print(str(nl))
print(str(vals))
print(str(nl)) vals.append(99)
print(str(vals))
vals.append(99) print(str(nl))
print(str(vals))
print(str(nl))
main()
``` ```
......
%% Cell type:markdown id:227f88f0 tags: %% Cell type:markdown id:227f88f0 tags:
# Sphere Volume # Sphere Volume
%% Cell type:code id:695f4dd5 tags: %% Cell type:code id:695f4dd5 tags:
``` python ``` python
""" """
Program to estimate the volume of a sphere by counting the Program to estimate the volume of a sphere by counting the
number of random points that fall inside compared with the number of random points that fall inside compared with the
number of points in a box round the sphere. number of points in a box round the sphere.
""" """
import math import math
import random import random
def random_point(max_range): def random_point(max_range):
""" """
Return a random 3d point in range +/max_range Return a random 3d point in range +/max_range
""" """
x = random.uniform(-max_range,max_range) x = random.uniform(-max_range,max_range)
y = random.uniform(-max_range,max_range) y = random.uniform(-max_range,max_range)
z = random.uniform(-max_range,max_range) z = random.uniform(-max_range,max_range)
return x,y,z return x,y,z
def point_in_sphere(radius,x,y,z): def point_in_sphere(radius,x,y,z):
""" """
Check if a point is within a sphere specified. Check if a point is within a sphere specified.
""" """
if x*x + y*y + z*z <= radius*radius: if x*x + y*y + z*z <= radius*radius:
return True return True
else : else :
return False return False
def main(): def main():
""" """
Main program Main program
""" """
points = int(input("Number of points : ")) # Ask for initial conditions points = int(input("Number of points : ")) # Ask for initial conditions
radius = float(input("Radius of sphere : ")) radius = float(input("Radius of sphere : "))
# Counters for number inside and look variable # Counters for number inside and look variable
inside, p = 0 , 0 inside, p = 0 , 0
while p <= points: # Loop over number of trial points while p <= points: # Loop over number of trial points
x,y,z = random_point(radius) # Random point in cube round sphere x,y,z = random_point(radius) # Random point in cube round sphere
if point_in_sphere(radius,x,y,z) : # Is it inside, if so count it if point_in_sphere(radius,x,y,z) : # Is it inside, if so count it
inside += 1 inside += 1
p += 1 p += 1
# Estimated volume is given by ratio of number of points inside # Estimated volume is given by ratio of number of points inside
# times volume of cube round sphere # times volume of cube round sphere
#
estimate = float(inside)/float(points)*math.pow(2*radius,3) estimate = float(inside)/float(points)*math.pow(2*radius,3)
vol = 4.0*math.pi*math.pow(radius,3)/3.0 vol = 4.0*math.pi*math.pow(radius,3)/3.0
print("Estimate volume is : " + str(estimate) + " real volume is : " + str(vol)) print("Estimate volume is : " + str(estimate) + " real volume is : " + str(vol))
main() main()
``` ```
......
%% Cell type:markdown id:74c83032 tags: %% Cell type:markdown id:74c83032 tags:
# Temperature Converter # Temperature Converter
%% Cell type:code id:e7d790d3 tags: %% Cell type:code id:e7d790d3 tags:
``` python ``` python
""" """
Simple converter between Fahrenheit and centigrade using functions Simple converter between Fahrenheit and Celsius degrees using functions
""" """
def fahrenheit(t): def fahrenheit(t):
""" """
Convert centigrade to fahrenheit Convert Celsius to Fahrenheit
""" """
return 1.8*t + 32 return 1.8*t + 32
def centegrade(t): def celsius(t):
""" """
Convert fahrenheith to centegrade Convert Fahrenheit to Celsius
""" """
return (t - 32.0)/1.8 return (t - 32.0)/1.8
def main(): # Main program # Main program
freezing = 0.0
boiling = 100.0
freezing = 0.0 print("Water freezes as : " + str(freezing) + " C or " + str(fahrenheit(freezing)) + " F")
boiling = 100.0 print("Water boils as : " + str(boiling) + " C or " + str(fahrenheit(boiling)) + " F")
print("Water freezes as : " + str(freezing) + " C or " + str(fahrenheit(freezing)) + " F") normalbody = 98.6
print("Water boils as : " + str(boiling) + " C or " + str(fahrenheit(boiling)) + " F") deathvalley = 134.0
normalbody = 98.6 print("Normal body temperature is : " + str(normalbody) + " F or " + str(celsius(normalbody)) + " C")
deathvalley = 134.0 print("Death Valley record is : " + str(deathvalley) + " F or " + str(celsius(deathvalley)) + " C")
print("Normal body temperature is : " + str(normalbody) + " F or " + str(centegrade(normalbody)) + " C")
print("Death Valley record is : " + str(deathvalley) + " F or " + str(centegrade(deathvalley)) + " C")
main()
``` ```
......
%% Cell type:markdown id:e477673e tags: %% Cell type:markdown id:e477673e tags:
# Three Way Conditional # Three Way Conditional
%% Cell type:code id:d0274b5d tags: %% Cell type:code id:d0274b5d tags:
``` python ``` python
""" """
Three way conditional example Three way conditional example
""" """
import math import math
def main(): a = float(input("Give a float : "))
a = float(input("Give a float : "))
if a > 4.0 :
# Inside if
b = 4.0 - math.sqrt(a)
a = 2.0*(b - 3.0)
print("if statements executed")
elif a > 0 :
# Inside else is
b = 1.0 + math.sqrt(a)
a = (b - 1.0)
print("elif statements executed")
else :
# Inside else
b = 4.0 - 3.0*math.sqrt(-a)
a = 7.0*(b - 3.0)
print("else statements executed")
# Outside conditional if a > 4.0 :
print("The value of a is : " + str(a) + " and b is : " + str(b)) # Inside if
b = 4.0 - math.sqrt(a)
a = 2.0*(b - 3.0)
print("if statements executed")
elif a > 0 :
# Inside else is
b = 1.0 + math.sqrt(a)
a = (b - 1.0)
print("elif statements executed")
else :
# Inside else
b = 4.0 - 3.0*math.sqrt(-a)
a = 7.0*(b - 3.0)
print("else statements executed")
main() # Outside conditional
print("The value of a is : " + str(a) + " and b is : " + str(b))
``` ```
......
%% Cell type:markdown id:05cd9aca tags: %% Cell type:markdown id:05cd9aca tags:
# Two Way Conditional # Two Way Conditional
%% Cell type:code id:615a5d55 tags: %% Cell type:code id:615a5d55 tags:
``` python ``` python
""" """
A Two way conditional example A Two way conditional example
""" """
def main(): a = int(input("Give an integer : "))
a = int(input("Give an integer : "))
if a < 10 : if a < 10 :
# Inside true of conditional # Inside true of conditional
print("The integer you gave was less that 10, give a bigger one.") print("The integer you gave was less that 10, give a bigger one.")
a = int(input("Give a bigger integer : ")) a = int(input("Give a bigger integer : "))
else: else:
# Inside false of conditional # Inside false of conditional
print("The integer you gave was big enough.") print("The integer you gave was big enough.")
# Outside conditional # Outside conditional
print ("The integer you gave was : " + str(a)) print ("The integer you gave was : " + str(a))
main()
``` ```
......
%% Cell type:markdown id:15c99cef tags: %% Cell type:markdown id:15c99cef tags:
# While Loop to List # While Loop to List
%% Cell type:code id:a90d92d5 tags: %% Cell type:code id:a90d92d5 tags:
``` python ``` python
""" """
Example to demonstrate a while loop to write theta and cos theta Example to demonstrate a while loop to write theta and cos theta
to a list to a list
""" """
import math import math
def main(): n_point = 50
n_point = 50 delta_theta = 2.0*math.pi/n_point # theta increment
delta_theta = 2.0*math.pi/n_point # theta increment theta = 0.0 # theta start
theta = 0.0 # theta start theta_data = [] # empty list
theta_data = [] # empty list cos_data = [] # empty list
cos_data = [] # empty list
while theta < 2.0*math.pi: # while loop
cos = math.cos(theta)
while theta < 2.0*math.pi: # while loop theta_data.append(theta) # Add values to list
cos = math.cos(theta) cos_data.append(cos)
theta_data.append(theta) # Add values to list theta += delta_theta # increment theta
cos_data.append(cos)
theta += delta_theta # increment theta # Do a default print (not very tidy output, replace this and
# a loop and make it nicer)
# Do a default print (not very tidy output, replace this and print(str(theta_data))
# a loop and make it nicer) print(str(cos_data))
print(str(theta_data))
print(str(cos_data))
main()
``` ```
......
%% Cell type:markdown id:fa29e737 tags: %% Cell type:markdown id:fa29e737 tags:
# Write File # Write File
%% Cell type:code id:2812565f tags: %% Cell type:code id:2812565f tags:
``` python ``` python
""" """
Example to open and write text strings, (and add a bit of culture) Example to open and write text strings, (and add a bit of culture)
""" """
def main(): fileout = open("burns.txt","w")
fileout = open("burns.txt","w")
fileout.write("When chapman billies leave the street,\n") fileout.write("When chapman billies leave the street,\n")
fileout.write("And drouthy neebors, neebors meet,\n") fileout.write("And drouthy neebors, neebors meet,\n")
fileout.write("As market-days are wearing late,\n") fileout.write("As market-days are wearing late,\n")
fileout.write("An' folk begin to tak the gate;\n") fileout.write("An' folk begin to tak the gate;\n")
fileout.write("While we sit bousing at the nappy,\n") fileout.write("While we sit bousing at the nappy,\n")
fileout.write("And getting fou and unco' happy,\n") fileout.write("And getting fou and unco' happy,\n")
fileout.write("We think na on the lang Scots miles,\n") fileout.write("We think na on the lang Scots miles,\n")
fileout.write("The mosses, waters, slaps and styles,\n") fileout.write("The mosses, waters, slaps and styles,\n")
fileout.write("That lie between us and our hame,\n") fileout.write("That lie between us and our hame,\n")
fileout.write("Whare sits our sulky sullen dame,\n") fileout.write("Whare sits our sulky sullen dame,\n")
fileout.write("Gathering her brows like gathering storm,\n") fileout.write("Gathering her brows like gathering storm,\n")
fileout.write("Nursing her wrath to keep it warm.\n") fileout.write("Nursing her wrath to keep it warm.\n")
fileout.write("\nRobert Burns\n") fileout.write("\nRobert Burns\n")
fileout.close() fileout.close()
main()
``` ```
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment