amgm.c

language: C
license: GPL 2

Code for Snippet:

                
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <float.h>
 
double          amgm(double, double, double);
double          am(double, double);
double          gm(double, double);
 
#define MAX(x,y) (x) > (y) ? (x) : (y)
#define MIN(x,y) (x) > (y) ? (y) : (x)
#define SUCCESS 0
#define FAILURE 1
#define DEFAULT 1e-15
 
int 
main(int argc, char *argv[])
{
    double          x, y, e;
    if (argc < 3) {
        printf("not enough arguments\n");
        exit(FAILURE);
    }
    x = strtod(argv[1], (char **) NULL);
    y = strtod(argv[2], (char **) NULL);
    if (MIN(x, y) < 0) {
        printf("numbers averaged must be non-negative\n");
        exit(FAILURE);
    }
    e = (argc == 3) ? DEFAULT : strtod(argv[3], (char **) NULL);
    if (e < DBL_MIN) {
        printf("precision must be positive\n");
        exit(FAILURE);
    }
    printf("%20.10f\n", amgm(x, y, e));
    return (SUCCESS);
}
 
double 
amgm(double x, double y, double eps)
{
    double          a = MAX(x, y), b = MIN(x, y);
    while ((a - b) > eps) {
        a = am(x, y);
        b = gm(x, y);
        x = a;
        y = b;
    }
    return (a);
}
 
double 
am(double x, double y)
{
    return ((x + y) / 2.0);
}
 
double 
gm(double x, double y)
{
    return (sqrt(x * y));
}
 
comments powered by Disqus

Info

Link to this snippet:


Download to Code Collector

To use the direct link to your snippet on CodeCollector.net either copy the html from the above section or drag the Download to Code Collector to where you would like to use it.

More Info:

Times Viewed: 624
Date Added: 2013-03-07 17:14:39
Last Modified: 2013-04-17 22:12:19

Web Analytics