|
CS 3343/3341 Analysis of Algorithms Fall 2012 Recitation 3 Big-Θ, Etc. Partial Answers |
// Harmonic.java: harmonic function
public class Harmonic {
static double harmonic0(int n) {
double res = 0.0;
while (n > 0) {
res += 1.0/n;
n = n - 1;
}
return res;
}
static double harmonic(int n) {
if (n == 1) return 1;
return 1.0/n + harmonic(n - 1);
}
public static void main(String[] args) {
int n = 1000000000;
double res;
System.out.println("harmonic0:\n");
res = harmonic0(n);
System.out.println(res);
System.out.println("harmonic:\n");
res = harmonic0(n);
System.out.println(res);
System.out.println(res - Math.log(n));
}
} | // harmonic.c: harmonic function #include |
[with n = 1000000000 above, got, after 18 secs] harmonic0: 21.30048150234615 [another 18 secs] harmonic: 21.30048150234615 0.57721 56653 99737 8 [Correct to 10 places. True value, Euler's Const: 0.57721 56649 01532 86060 65120] | [with N = 1000000000, got after 20 seconds] 21.3004815023434091 0.57721 56653 96998 6 [recursive part ran for N = 100000, gave segmentation fault with N = 1000000] |
// sqrt.c: find sqrt of input r
#include <stdio.h>
#include <math.h> // needed for fabs
double sqrt(double r) {
double x0 = 1, x1;
printf("%0.16f\n", x0);
for ( ; ; ) {
x1 = x0/2 + r/(2*x0);
printf("%0.16f\n", x1);
if (fabs(x1 - x0) < 1.0e-6) break;
x0 = x1;
}
return x1;
}
int main() {
double r, x;
scanf("%lf", &r);
x = sqrt(r);
printf("\nsqrt(%0.16f) = %0.16f\n", r, x);
printf("\nsqrt(r)^2 = %0.16f\n", x*x);
}
| % cc -o sqrt sqrt.c -Wall ./sqrt 10 1.0000000000000000 5.5000000000000000 3.6590909090909092 3.1960050818746470 3.1624556228038903 3.1622776651756750 3.1622776601683795 sqrt(10) = 3.1622776601683795 sqrt(r)^2 = 10.0000000000000018 |
// cosxeqx.c: find x such that cos(x) = x
#include <stdio.h>
#include <math.h> // needed for fabs
#include <stdlib.h> // needed for exit
double f(double x0) {
double x1;
printf("%20.16f\n", x0);
int i;
for (i = 0; i < 50000; i++ ) {
x1 = x0 + (cos(x0) - x0)/(sin(x0) + 1);
printf("%i: %0.16f\n", i, x1);
if (fabs(x1 - x0) < 1.0e-6) break;
x0 = x1;
}
return x1;
}
int main(int argc, char *argv[]) {
double r, x0;
if (argc != 2) {
printf("Usage: \"./cosxeqx 2\"\n");
exit(1);
}
sscanf(argv[1], "%lf", &x0);
r = f(x0);
// printf("\nroot = %0.16f\n", r);
// printf("check: cos(x) - x = %20.16f\n"
// cos(r) - r);
}
| % cc -o cosxeqx -lm cosxeqx.c -Wall ./cosxeqx 1 1.0000000000000000 0: 0.7503638678402439 1: 0.7391128909113617 2: 0.7390851333852839 3: 0.7390851332151607 root = 0.7390851332151607 check: cos(x) - x = -0.0000000000000001 |
