How can I generate random numbers for the demo charts that roughly match the top and right?

I need to generate random numbers for several charts that go up and to the right.

I'm using JavaScript's charting engine, so numbers will eventually be needed in JSON, but I can handle the conversion if you have an easy way outside of JavaScript.

Here's a simple random number generator in JavaScript:

function randomNumber(minimum, maximum){
    return Math.round( Math.random() * (maximum - minimum) + minimum);
}
console.log(randomNumber(0,100));

      

The above would work if min

u max

grew over time. Can you point me in the right direction?

Here's a JSFiddle to try various solutions, including a handy graph: http://jsfiddle.net/9ox4wjrf/

Here's an example that I have to build using the generated data:

rough example of desired results

+3


source to share


3 answers


Something like this might work:

var a = 0.05;
var b = 10; //play with these values to your liking
var y;

//loop here from 0 to whatever
y = a * x^2 + b * x * Math.random();
//or using your randomMumber function:
y = a * x^2 + randomMumber(- b * x / 2, b * x / 2);

      



Thus, the noise becomes greater as you go further to the right.

+4


source


Define your trend silently, like an array of growing numbers. Call this X and copy it to another Y array. Then, for each Y point, add the number generated by Math's built-in random number generator. This will add the illusion of noise.



If you want more random options, check out random-js on GitHub. https://github.com/mobiusklein/random-js . It's a great library, but forks help smooth out rough edges. Also, https://github.com/tmcw/simple-statistics for linear regression lines.

+2


source


It will be pseudocode, but you can do something like this:

int randomRangePotential = 20; // percentage of random growth/shrinkage
int likelyhoodOfGrowth = 95; // likelyhood of datapoint being more than the previous
int numberOfDataPoints = 100; // number of data points to generate

int lastDataPointValue = 50;

for (int iterator = 0; iterator < numberOfDataPoints; iterator++)
{
    // generate random number to determine positive or negative growth 0 - 100
    // generate randomRange, a random number between 1 and randomRangePotential
    // if random number > likelyhoodOfGrowth

       // generate random number for datapoint that is (lastDataPoint = lastDataPoint * 1.randomRange)
       // add the random number to a datapoint

    // if random number < likelyhoodOfGrowth

       // generate random number for datapoint that is (lastDataPoint = lastDataPoint * -1.randomRange)
       // add the random number to a datapoint

    // lastDataPointValue = thisdatapoint

}

      

+1


source







All Articles