view FloatHist.c @ 12:20410d90dabb

Expose HistFree
author Merten Sach <msach@mailbox.tu-berlin.de>
date Wed, 21 Sep 2011 14:00:20 +0200
parents 83a412f2ef98
children 1fbaedaac2c7
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 */
8 #include <stdio.h>
9 #include "Histogram.h"
10 #include "../vmalloc.h"
12 /*This Histogram Abstract Data Type has a number of bins, the starting
13 * value, and the width of each bin, as a float, all chosen at creation.
14 *
15 *One creates a Histogram instance using the makeFloatHistogram function, then
16 * updates it with the addToFloatHist function, and prints it out with the
17 * printFloatHist function.
18 *
19 *Note, the bin width is an integer, so the end of the range is adjusted
20 * accordingly. Use the bin-width to calculate the bin boundaries.
21 */
24 FloatHist *
25 makeFloatHistogram( int32 numBins, float32 startOfRange, float32 binWidth )
26 {
27 FloatHist *hist;
28 int i;
30 hist = VMS__malloc( sizeof(FloatHist) );
31 hist->bins = VMS__malloc( numBins * sizeof(int) );
33 hist->numBins = numBins;
34 hist->binWidth = binWidth;
35 hist->endOfRange = startOfRange + hist->binWidth * numBins;
36 hist->startOfRange = startOfRange;
38 for( i = 0; i < hist->numBins; i++ )
39 {
40 hist->bins[ i ] = 0;
41 }
43 return hist;
44 }
47 /*All values higher than or equal to a bin's start value and less than the
48 * start value of the next higher are put into that bin.
49 */
50 void
51 addToFloatHist( float32 value, FloatHist *hist )
52 {
53 int binIdx;
55 if( value < hist->startOfRange )
56 { binIdx = 0;
57 }
58 else if( value > hist->endOfRange )
59 { binIdx = hist->numBins - 1;
60 }
61 else
62 { //truncate so bin holds: binStartVal =< values < nextBinStartVal
63 binIdx = (int32)((value - hist->startOfRange) / hist->binWidth);
64 }
66 hist->bins[ binIdx ] += 1;
67 }
69 void
70 printFloatHist( FloatHist *hist )
71 {
72 int32 binIdx, i, numBars, maxHeight;
73 float32 barValue, binStart, binEnd;
75 maxHeight = 0;
76 for( i = 0; i < hist->numBins; i++ )
77 {
78 if( maxHeight < hist->bins[ i ] ) maxHeight = hist->bins[ i ];
79 }
80 barValue = maxHeight / 40; //40 spaces across page for tallest bin
82 printf("histogram: \n");
83 if( barValue == 0 ) printf("error printing histogram\n");
84 for( binIdx = 0; binIdx < hist->numBins; binIdx++ )
85 {
86 binStart = hist->startOfRange + hist->binWidth * binIdx;
87 binEnd = binStart + hist->binWidth;
88 printf("bin range: %3f - %3f", binStart, binEnd );
90 numBars = hist->bins[ binIdx ] / barValue;
91 //print one bin, height of bar is num dashes across page
92 for( i = 0; i < numBars; i++ )
93 {
94 printf("-");
95 }
96 printf("\n");
97 }
98 }
101 void
102 freeFloatHist( FloatHist *hist )
103 {
104 VMS__free( hist->bins );
105 VMS__free( hist );
106 }