view DblHist.c @ 2:06128e387cfa

Added DblHist and FloatHist
author Me
date Sat, 30 Oct 2010 22:13:09 -0700
parents
children 3d35477a5121
line source
1 /*
2 * Copyright 2010 OpenSourceStewardshipFoundation.org
3 * Licensed under GNU General Public License version 2
4 *
5 * Author: seanhalle@yahoo.com
6 *
7 */
9 #include "Histogram.h"
10 #include <malloc.h>
13 /*This Histogram Abstract Data Type has a number of bins, the starting
14 * value, and the width of each bin, as a float, all chosen at creation.
15 *
16 *One creates a Histogram instance using the makeFloatHistogram function, then
17 * updates it with the addToFloatHist function, and prints it out with the
18 * printFloatHist function.
19 *
20 *Note, the bin width is an integer, so the end of the range is adjusted
21 * accordingly. Use the bin-width to calculate the bin boundaries.
22 */
25 DblHist *
26 makeDblHistogram( int32 numBins, float64 startOfRange, float64 binWidth )
27 {
28 DblHist *hist;
29 int i;
31 hist = malloc( sizeof(DblHist) );
32 hist->bins = malloc( numBins * sizeof(int) );
34 hist->numBins = numBins;
35 hist->binWidth = binWidth;
36 hist->endOfRange = startOfRange + hist->binWidth * numBins;
37 hist->startOfRange = startOfRange;
39 for( i = 0; i < hist->numBins; i++ )
40 {
41 hist->bins[ i ] = 0;
42 }
44 return hist;
45 }
48 /*All values higher than or equal to a bin's start value and less than the
49 * start value of the next higher are put into that bin.
50 */
51 void
52 addToDblHist( float64 value, DblHist *hist )
53 {
54 int binIdx;
56 if( value < hist->startOfRange )
57 { binIdx = 0;
58 }
59 else if( value > hist->endOfRange )
60 { binIdx = hist->numBins - 1;
61 }
62 else
63 { //truncate so bin holds: binStartVal =< values < nextBinStartVal
64 binIdx = (int32)((value - hist->startOfRange) / hist->binWidth);
65 }
67 hist->bins[ binIdx ] += 1;
68 }
70 void
71 printDblHist( DblHist *hist )
72 {
73 int32 binIdx, i, numBars, maxHeight;
74 float64 barValue, binStart, binEnd;
76 maxHeight = 0;
77 for( i = 0; i < hist->numBins; i++ )
78 {
79 if( maxHeight < hist->bins[ i ] ) maxHeight = hist->bins[ i ];
80 }
81 barValue = maxHeight / 40; //40 spaces across page for tallest bin
83 printf( "histogram: \n" );
84 if( barValue == 0 ) printf( "error printing histogram\n" );
85 for( binIdx = 0; binIdx < hist->numBins; binIdx++ )
86 {
87 binStart = hist->startOfRange + hist->binWidth * binIdx;
88 binEnd = binStart + hist->binWidth;
89 printf( "bin range: %.6fl - %.6fl", binStart, binEnd );
91 numBars = hist->bins[ binIdx ] / barValue;
92 //print one bin, height of bar is num dashes across page
93 for( i = 0; i < numBars; i++ )
94 {
95 printf("-");
96 }
97 printf("\n");
98 }
99 }