Tips and tricks #12: Long (infinite) calculations

This article describes how to perform long or infinite calculations while allowing user to stop them

Tips and tricks series

This article may rely on knowledge you should get from previous articles, so you may want to check them first.

To use this feature you have to check the calculator option "Long (infinite) calculation". With this option, your calculation will be performed on a separate thread by the web worker as series of calculations, allowing user to stop them if he wishes.

Technically, with this mode, you are given the progressControl object, which should be used to organize series of calculations, with the help of context property, which is carried from calculation to calculation and stop and repeat methods to stop series or schedule next calculation respectively. Below you can find a code snippet that demonstrates this technique.

if (n === 0) return PCR.integer(1);

if (!progressControl.context) {
    //set the default values for output parameters
    factorial.SetValue('1! = 1');   
    //initialize the context
    progressControl.context = {
        current: PCR.integer(1),
        m: 1
    };
    //schedule next iteration
    progressControl.repeat();
} else {
    //get the context
    var data = progressControl.context;
    //perform the calculations
    data.current = data.current.mul(++data.m);
    //update the output parameters
    factorial.SetValue(data.m + '! = ' + data.current.toString());    
    //stop the iterations or schedule next iteration
    if (data.m != n)
        progressControl.repeat();
    else 
        progressControl.stop();
}

That's it. And you can check the result below, just enter something around 1000 at least

PLANETCALC, Factorial

Factorial

Factorial n!
 

URL copiada al portapapeles
PLANETCALC, Tips and tricks #12: Long (infinite) calculations

Comentarios