About a year ago, I wrote an algorithm to take the range of some data and output the value of each axis gradation. That is, tell the user how to space their graph. Click the read more button to see it in C++ and Ruby. I also implemented it in Javascript as a web page here.

Here it is in C++:

#include <iostream>
#include <math.h>
#include <cstdio>
int toGraphNum(double x)
{
if(x < 1) { return 1; }
if(x < 2) { return 2; }
if(x < 5) { return 5; }
if(x > 5) { return 10; }
}
int graphScaler(double largest, double smallest, int squares);
int graphScaler(double difference, int squares);
int main()
{
double largest;
double smallest;
int bigSquares;
std::cout << "Please enter the largest number:";
std::cin >> largest;
std::cout << "Please enter the smallest number:";
std::cin >> smallest;
double difference = abs(largest - smallest);
std::cout << "Please enter the number of big squares:";
std::cin >> bigSquares;
int bigSquareVal = graphScaler(difference, bigSquares);
std::cout << "Each big square is worth: " << bigSquareVal << std::endl;
//Utilisation = {plotted data range}/{total axis range = amount per square * count(squares)}
std::cout << "Graph utilisation percentage = " << difference / (bigSquareVal * bigSquares) * 100 << std::endl;
std::cout << "Press enter to continue...";
std::cin.get();
return 0;
}
int graphScaler(double largest, double smallest, int squares)
{
graphScaler((static_cast(abs(largest - smallest)), squares);
}
int graphScaler(double difference, int squares)
{
double nastyGradation = (difference/squares);
int ngOrder = pow(10,floor(log10(nastyGradation)));
return toGraphNum(nastyGradation/ngOrder) * ngOrder;
}

Here it is in Ruby (you could run it on your phone with Ruboto IRB):

def toNN(num)
return 1 if(num < 1)
return 2 if(num < 2)
return 4 if(num < 4)
return 5 if(num < 5)
return 10 if(num > 5)
end
def graphScaler(difference, squares)
ng = difference/squares
ngOrder = 10 ** Math.log(ng).floor
return toNN(ng/ngOrder) * ngOrder
end
#Shortcut
def gs(d,s)
return graphScaler(d,s);
end

### Like this:

Like Loading...