/*
 *  horner.c
 *  
 *
 *  Created by Jannis Andrija Schnitzer on 4/25/09.
 *  Copyright 2009 Jannis Andrija Schnitzer.
 *  
 Copyright (c) 2009 Jannis Andrija Schnitzer
 
 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:
 
 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.
 
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE. 
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

typedef long double number_t;
enum {
    NORMAL,
    HORNER
} mode;

/* These values could be read from the user */
#define LENGTH 10000
#define START -1.07
#define STOP 1.07
#define STEP 0.01

number_t
my_pow(number_t x, int n)
{
    if (n == 0)
    {
        return 1;
    }
    else
    {
        return x * my_pow(x, n-1);
    }
}

number_t
normal(number_t a[], int length, number_t x)
{
    int n;
    number_t result = 0;
    for (n = 0; n < length; n++)
    {
        result += a[n] * powl(x, n);
    }
    return result;
}

number_t
horner(number_t a[], int length, number_t x)
{
    int n = length-1;
    number_t result = a[n]; /* that's a[n] */
    for (n = n - 1; n >= 0; n--)
    {
        result = (result * x) + a[n]; /* No power here */
    }
    return result;
}

int
main(int argc, char **argv)
{
    int i;
    number_t (*func)(number_t*, int, number_t) = horner;
    number_t a[LENGTH];
    number_t x, result;
    
    /* fill array */
    for (i = 0; i < length; i++) {
        a[i] = length-i;
    }
    
    if (argc > 1)
    {
        if (strcmp(argv[1], "normal") == 0)
        {
            func = normal;
        }
    }
    
    for (x = START; x <= STOP; x += STEP)
    {
        result = (*func)(a, length, x);
        printf("f(%Lf) = %Lf\n", x, result);
    }
    return 0;        
}
