Due Date: Thursday 27 @ 10:30 AM. This homework aims at giving you some experience with values, variables, types, and assignments in programming.





1.  Type the following in the command window and submit the results. Briefly explain what each assignment does.

a = 1
b = 'x'
c = true
whos a b c
a == c
a + c
d = [1 2 3 4]
e = ['a' 'b' 'c' 'd']
f = ['a','b','c','d']
g = ['abcd']
h = {‘a’ ‘b’ ‘c’ ‘d’}
i = { a b c d}
whos d e f g h i
class(a)
type(a)
True
true
False
false


Answer:
In MATLAB:

a = 1                   % assigns value 1 to a
b = 'x'                 % assigns character 'x' to b
c = true                % assigns logical value true to variable c
whos a b c              % prints a description of the variables a b c
a == c                  % evaluates whether a euqals b
a + c                   % returns sum of a and c
d = [1 2 3 4]           % creates a real array
e = ['a' 'b' 'c' 'd']   % creates a string 'abcd'
f = {'a','b','c','d'}   % creates a cell array of the input 4 characters
g = ['abcd']            % creates a string 'abcd'
h = {‘a’ ‘b’ ‘c’ ‘d’}   % syntax error due to use of undefined characters ‘ and ’
i = { a b c d}          % creates a cell array from the four input variables
whos d e f g h i        % prints a description of the variables d e f g h i
class(a)                % returns the type of the variable a
type(a)                 % syntax error: input arguments to type() must be character vectors or strings
True                    % syntax error: undefined variable
true                    % logical value true in MATLAB
False                   % syntax error: undefined variable
false                   % logical value false in MATLAB

In Python, a lot of the above commands would yield syntax errors, however, many of them can be easily fixed with minor tweaks.





2.  Overflow. What would happen if you went beyond the range for a particular type? For example, the largest integer that can be stored in int8 is 127, and the smallest integer is -128, so what would happen if we type cast a larger integer to the type int8? Smaller integer? Use the MATLAB built-in functions intmin and intmax or Python’s numpy package command iinfo to find the largest and smallest integers that can be stored in int16 and int32.

Answer:
The resulting behavior is language-dependent. In MATLAB, the overflow and underflow as of today freeze to the largest or smallest possible values that could be represented by that variable type. In python, it leads to rollover or perhaps random value assignments to the variable. Here is the results in MATLAB:

>> int8(200)
ans =
  int8
   127
>> int8(-150)
ans =
  int8
   -128
>> intmax('int16')
ans =
  int16
   32767
>> intmin('int16')
ans =
  int16
   -32768
>> intmax('int32')
ans =
  int32
   2147483647
>> intmin('int32')
ans =
  int32
   -2147483648





3.  Operator Precedence. Think about what the results would be for the following expressions, and then type them in to the terminal to verify your answers. Briefly explain the results for each one.

>> 1\2 
>> 1/2
>> int8(1/2)
>> int8(1/3)
>> -5^2  
>> -5**2  
>> (-5) ^ 2 
>> (-5) ** 2 
>> 10-6/2 
>> 5*4/2*3


Answer: Here is the output in MATLAB:

>> 1\2
ans =
     2
>> 1/2
ans =
    0.5000
>> int8(1/2)
ans =
  int8
   1
>> int8(1/3)
ans =
  int8
   0
>> -5^2
ans =
   -25
>> (-5)^2
ans =
    25
>> 10-6/2
ans =
     7
>> 5*4/2*3
ans =
    30

However, note that the same results would not hold in Python.





4.  Provide three different methods of generating the matrix a, one method should use the diag() function, one should use the eye function, and one should use the zeros function.

>> a
a =
     2     0     0
     0     2     0
     0     0     2

Answer:
Here is the output in MATLAB. Similar results can be achieved in Python, by using the same function names as in MATLAB, but via Python’s numpy package.

>> a = eye(3,3) * 2
a =
     2     0     0
     0     2     0
     0     0     2
>> d = [2 2 2]
d =
     2     2     2
>> a = diag(d)
a =
     2     0     0
     0     2     0
     0     0     2


>> a = zeros(3,3);
>> a(1,1) = 2;
>> a(2,2) = 2;
>> a(3,3) = 2;
>> a
a =
     2     0     0
     0     2     0
     0     0     2





5.  MATLAB. Download this code. This code is full syntax errors. Fix the errors and submit the corrected code with name script_full_of_errors_fixed.m in your folder for this HW. Explain in front of each corrected MATLAB statement, why the error occurred. Modify the last two variables so that they display,

>> Persian
Persian =
Persian is a human language
>> Spanish
Spanish = 
    'Spanish '    'is '    ' another'    'language'


Modify the last line such that for the last line the code displays,

Persian is not the same as Spanish


Explain these results.

Answer:
The corrected script can be found here





6.  Python. Download this Python script. This Python script is full of syntax, runtime, and semantic errors. Please identify and corrent these errors, such that code becomes fully executable and outputs the following message on the screen, when run from the Git Bash command line:

The life expectancy for the millennials is projected to be 120 years! (But don't believe it...)


    A recent study published in the journal of Nature, discovered that over the past century,
    although the life expectancy has significantly increased due to technological advances,
    the maximum life span of the oldest people in the world has not changed much.


Cardano was the first to introduce complex numbers of the form a + sqrt(-b) into algebra, but he had misgivings about it.
In his solution to an algebra equation he encountered the solution 5 + sqrt(-15) for the unknown, which is now mathematically represented by

       (5+3.872983346207417j)

in Python, which can also be obtained as an addition of real and imaginary numbers in Python like this


      5 + sqrt(-15) = (5+3.872983346207417j),


      which can also be manually stated as


      (5+3.872983346207417j)





One final note:

        In python the sqrt function from math and cmath modules are different.
        The sqrt function that returns "float" results is sqrt from math module.
        Therefore, if using math module, then,

                sqrt(25) = 5.0000,

        which is obviously a float (real number).




Also note that by convention, 0**0 = 1 in Python.
And division by 0, will give you a runtime exception: 1/0 = NaN


Identify at least one example in the code for each of the error types.

Here are a few hints:

  • You need to get familiar with string formatting in print function. See Lecture 4.

  • Note that in Python, the interpreter is sensitive to indentations in your codes. All lines must be aligned at the beginning (except for looping and branching, … which we will get to them later on).

  • Become familiar with escape characters in Python, such as '\n', '\t', and '\t'.

Answer:
The corrected file can be downloaded from here. Examples of different types of programming errors:

  1. semantic error example:

    • line 15, in the wrong script: The purpose is to print the complex number 5+sqrt(-15), but instead 5-15j is printed by the wrong script.

    • line 35, in the wrong script: The purpose is to print float number, but since we used sqrt from cmath module, the output is in complex format, which is not what we intend to obtain and print.

  2. runtime error example:

    • in line 45, in the wrong script, division by zero, is a runtime exception.

  3. syntax error example:
    Almost any other error in the code is a syntax error. For example, lines 11,12,13 should be aligned, but they are not.





7.  MATLAB. Use MATLAB help to find out how you can create a new directory named mynewdir from MATLAB command line. Then change the working directory the newly created directory. Then create a MATLAB script in this directory named myscript.m with the following code in it,

% First create an array from -2*pi to 2:pi
x = -2*pi:pi/20:2*pi;

% Calculate |sin(x)|
y = abs(sin(x));

plot(x,y);


Now on MATLAB command line, run the script by calling its name. What do you get? Save the output as a figure and submit it with your homework.

Answer:

You can create a new directory and switch the current directory to it using the following commands,

>> mkdir mynewdir
>> cd mynewdir


The script myscript generates a plot of $y$ versus $x$ where $y = |sin(x)|$. In doing so, MATLAB opens a new window called plot window that contains the plot of y as a function of x. Here is the resulting figure:





8.  MATLAB. Now change your working directory to the original directory before you created mynewdir directory. Try to run the script myscript you had created again, from MATLAB command line. What do you get? and why?

Answer:

You get an error message like the following,

>> cd mynewdir\
>> myscript
>> cd ..
>> myscript
Undefined function or variable 'myscript'.


And this happens because the script we are trying to run is neither in MATLAB’s working directory, nor in any of MATLAB’s search paths. Therefore, MATLAB gives an error, as it cannot find the requested file.





9.  Python Write a Python script that is directly executable from the Git Bash command line, without any need to invoke python interpreter. The script should produce exactly the following output, including line breaks and separations. Each part of the output (separated by a line-break, or a new-line character '\n' from the rest) is generated by only and only one call to print function.

This is Python version 3.5.2 

Python is the best language for String manipulation!

!noitalupinam gnirtS rof egaugnal tseb eht si nohtyP

!otlpnmgit o gunlte h inhy

pYTHON IS THE BEST LANGUAGE FOR sTRING MANIPULATION!


The sentence 'Python is the best language for String manipulation!' contains 
4 'a' letters, and
0 'A' letters!

Python
is
the
best
language
for
String
manipulation!

PYTHON
IS
THE
BEST
LANGUAGE
FOR
STRING
MANIPULATION!


Here are some hints (all the information you need to answer this question can be found in the lecture notes):

  • To make the script executable, add the appropriate shebang to the script’s file.

  • Import the appropriate module to get the python version command, as we did in class. Use print function to print the Python version.

  • Define a String variable my_string which contains the string value “Python is the best language for String manipulation!” ( Of course, you can totally accomplish this question without defining a string variable, by only using the string value itself wherever needed… This is also totally fine at this point in our course, if your prefer this method).

  • Then use the appropriate examples and external links provided in the lecture notes, to find the proper string methods that can manipulate this string variable/value in order to generate each of the outputs printed above.

  • Again, note that for each output, the entire output must result from one single call to function print.

  • Wherever needed, use the escape character value '\n' in print input arguments, in order to generate a line-break (or new line) in the output.

Answer:
A working Python script file can be downloaded from here.





10.  The bell-shaped Gaussian probability density function,


is one of the most widely used functions in science and technology. The parameters of the function (mu,sigma>0) are prescribed real numbers. Write a program for evaluating this function when $\mu=0$, $\sigma=2$, $x = 1$.

Hint: The value pi, and exp() , sqrt() function are built-in in MATLAB, but are not so in Python. You will need to export them using the following command in Python,

from math import pi, exp, sqrt


Verify your answer by getting the same result from Wolfram Alpha mathematical search engine.

Answer:
A version of the code in Python can be downloaded from here.





11.  Python. Download this code. This code is full syntax errors. Fix the errors and submit the corrected code with name script_full_of_errors_corrected.py in your hw4 folder of your project. Explain in front of each corrected Python statement, why the error occurred. On the last line of the script,

true = fox is rev in Persian


the statement runs without error. But can you explain what it does? (Hint: For this part you need to understand operation precedence. You can find more information here.

Answer:
The corrected file can be downloaded from here.





12.  As an egg cooks, the proteins first denature and then coagulate. When the temperature exceeds a critical point, reactions begin and proceed faster as the temperature increases. In the egg white, the proteins start to coagulate for temperatures above $63^\circ\rm{C}$, while in the yolk the proteins start to coagulate for temperatures above $70^\circ\rm{C}$. For a soft boiled egg, the white needs to have been heated long enough to coagulate at a temperature above $63^\circ\rm{C}$, but the yolk should not be heated above $70^\circ\rm{C}$. For a hard boiled egg, the center of the yolk should be allowed to reach $70^\circ\rm{C}$.

The following formula expresses the time $t$ it takes (in seconds) for the center of the yolk to reach the temperature Ty (in Celsius degrees):


where $M$ is the mass of egg, $\rho$ is the density, $c$ is the specific heat capacity, and $K$ is thermal conductivity. Relevant values are $M=47~[g]$ for a small egg and $M=67~[g]$ for a large egg, $\rho=1.038 ~[g~cm^{-3}]$, $c = 3.7 ~[J~g^{-1}~K^{-1}]$, and $K = 5.4\times10^{-3} ~[Wcm^{-1}K^{-1}]$. Furthermore, $T_w$ is the temperature (in C degrees) of the boiling water, and $T_0$ is the original temperature (in C degrees) of the egg before being put in the water. Implement the formula in a Python/MATLAB program, set $T_w = 100^\circ C$ and $T_y = 70^\circ C$, and compute $t$ for a large egg taken from the fridge ($T_0 = 4^\circ C$) and from room temperature ($T_0 = 20^\circ C$). (Hint: Note that for this problem you will need to import log, pi from math module in Python, but these are intrinsic in MATLAB.)

Answer:
A version of the code can be downloaded from here.





13.  Python: Aliasing vs. Copying variables. Run the following python statements and briefly explain why you get the behavior printed by the print functions.

(A)

a = 5
b = a
print (id(a), id(b))
 
c = b
b = 3
print (a,b,c)
print (id(a),id(b),id(c))
 
b = a
b = 5
print (id(a), id(b))


(B)

a = [5]
b = a
print (id(a), id(b))
 
b.append(1)
print a,b
print (id(a),id(b))


(C)

a = [5]
b = list(a)
print (a,b)
print (id(a), id(b))
 
b = a[:]
print (a,b)
print (id(a), id(b))


(D)

a = (5,)
b = tuple(a)
print (id(a), id(b))
 
b = a[:]
print (id(a), id(b))

Answer:

(A)

# Assign a value to a new variable
a = 5
 
# Create an alias identifier for this variable
b = a
 
# Observe how they refer to the same variable!
print (id(a), id(b))
 
# Create another alias
c = b
 
# Now assign a new value to b!
b = 3
 
# And observe how a and c are still the same variable
# But b is not
print (a,b,c)
print (id(a),id(b),id(c))
 
# Now for another quirk, suppose we do this:
b = a
b = 5
 
# We used an assignment, but the value didn't actually change
# So the alias remains unbroken
print (id(a), id(b))


(B)

# Create a new <list>
a = [5]
 
# Create an alias identifier for this list
b = a
print (id(a), id(b))
 
# Now change the <list> b in-place
b.append(1)
 
# And observe how this also changes a
# The alias is not broken by in-place operations
print (a,b)
print (id(a),id(b))


(C)

# Create a <list>
a = [5]
 
# Create a new <list> with the same value
b = list(a)
 
# We now have two separate variables with identical but separate values
print (a,b)
print (id(a), id(b))
 
# Same with the full slice technique:
b = a[:]
print (a,b)
print (id(a), id(b))


(D)

# Create <tuple>
a = (5,)
 
# Try to force a copy
b = tuple(a)
 
# It didn't work...
print (id(a), id(b))
 
# Neither does this
b = a[:]
print (id(a), id(b))





14.  Python. The following is the name list of all people in our class.

Christian-Andrew Bagby-wright
Matthew Chrysler
Niyousha Davachi
Pauline Dredger
Marcos Guillen
Lauren Kuffel
Shashank Kumbhare
Hany Mahdy
Sarah Moorman
Andrew Myers
Joshua Osborne
Rebecca Proni
Amir Shahmoradi
Carolina Vedovato


We want to create a dictionary of members of this class with individuals’ full names serving as dictionary keys, and their roles in class as the corresponding values of the keys. The naive way of generating this dictionary would be to use one of the methods for generating dictionary discussed in the lecture notes. For example,

class_dict  = { 
            , 'Christian-Andrew Bagby-wright' : 'student'
            , 'Matthew Chrysler'              : 'student'
            , 'Niyousha Davachi'              : 'student'
            , 'Pauline Dredger'               : 'student'
            , 'Marcos Guillen'                : 'student'
            , 'Lauren Kuffel'                 : 'student'
            , 'Shashank Kumbhare'             : 'student'
            , 'Hany Mahdy'                    : 'student'
            , 'Sarah Moorman'                 : 'student'
            , 'Andrew Myers'                  : 'student'
            , 'Joshua Osborne'                : 'student'
            , 'Rebecca Proni'                 : 'student'
            , 'Amir Shahmoradi'               : 'instructor'
            , 'Carolina Vedovato'             : 'student'
            }


However, the problem is that, except me (Amir, the instructor), everyone else has a student role in this class. So it would be a very painful process to type all ‘student’ values by hand manually. Now, the goal is to come up with a shortcut method that avoids the aforementioned problem. Can you find a way of creating this dictionary, without having to type the value ‘student’ 14 times? Note that in order to achieve this, you don’t need anything beyond what you learned in the lecture notes. (Hint: Have a look at the section for simultaneous assignments in the lecture notes.)

Answer:

class_dict = { 'amir shahmoradi'  : 'instructor'
           }
class_dict
{'amir shahmoradi': 'instructor'}
class_dict[ 'Christian-Andrew Bagby-wright' ] = \
class_dict[ 'Matthew Chrysler'              ] = \
class_dict[ 'Niyousha Davachi'              ] = \
class_dict[ 'Pauline Dredger'               ] = \
class_dict[ 'Marcos Guillen'                ] = \
class_dict[ 'Lauren Kuffel'                 ] = \
class_dict[ 'Shashank Kumbhare'             ] = \
class_dict[ 'Hany Mahdy'                    ] = \
class_dict[ 'Sarah Moorman'                 ] = \
class_dict[ 'Andrew Myers'                  ] = \
class_dict[ 'Joshua Osborne'                ] = \
class_dict[ 'Rebecca Proni'                 ] = \
class_dict[ 'Carolina Vedovato'             ] = 'student'
class_dict
{'amir shahmoradi': 'instructor',
'Christian-Andrew Bagby-wright': 'student',
'Matthew Chrysler': 'student',
'Niyousha Davachi': 'student',
'Pauline Dredger': 'student',
'Marcos Guillen': 'student',
'Lauren Kuffel': 'student',
'Shashank Kumbhare': 'student',
'Hany Mahdy': 'student',
'Sarah Moorman': 'student',
'Andrew Myers': 'student',
'Joshua Osborne': 'student',
'Rebecca Proni': 'student',
'Carolina Vedovato': 'student'}
type(class_dict)
dict

Later on, we will learn more effective methods of constructing this dictionary using Python’s for-loops.

Comments