-
Exercise (30 points)
-
(a) Write a RECURSIVE function Power(x,n) that computes xn
for double X and a non-negative integer n >=0.
-
(b) Now improve the running time of this function - Write the a version
of Power(x,n) that works by breaking n down to halfs (where half of n =
n/2), squaring Power(x,n/2), and multiplying by x again if n was odd.
For example, x11 = (x5)*(x5)*x,
whereas x10 = (x5)*(x5).
Find a suitable base case to stop the recursion.
Write your main function in a file "p1.c".
Note: Do not use this function on very large numbers.
What is the largest number a double type can hold?
-
Exercise (40 points)
The function sin(x) can be approximated for values of x which are close
to zero. This is done by a Tailor expansion - an infinite sum:
Write a function ,Sin_Approx(double angle, int M); that computes
the Tailor expansion up to the Mth element (this means that the summation
goes up until n = M, instead of infinity).
Your function should use the recursive factorial function (n! studied
in class) and the recursive function Power(x,n) from the previous exercise
(you can use a or b). Note, however, that it is time consuming to compute
a power of -1, so don't use the regular power function for that!
In order to test your function, you should write a program that computes
the sine of x using the sin(x) function from "math.h", and compares it
to the approximated Sin_Approx function. The format of the output should
be the following:
Sin(0) is 0.00, Sin_Approx(0) is 0.00
Your program should prompt the user for "x" (read and use as double) and
"M" (integer >=0).
What value should M have so that | Approx_Sin(0.333,M)-sin(0.333) |
< 0.0000000001 ?
Run your program to test it, and write the answer in the README
file you submit.
Write your main function in a file "p2.c".
-
Exercise (30 points)
Create a makefile that handles the following targets:
% make p1 (creates an executable p1 for exercise #1)
% make p2 (creates an executable p2 for exercise #2)
(the last two should create appropriate object files)
% make test1 (runs exercise #1 with "1.inp" as input file
and "1.out" as output file)
% make clean (deletes the object files, the executables and 1.out)
(Note, CVN students: this is a UNIX makefile, creating makefiles for
compilers on PC is only an option)