Tips and tricks #12: Long (infinite) calculations

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

Timur

• Article : Tips and tricks #12: Long (infinite) calculations - Author
• Calculator : Factorial - Author

Anton

• Calculator : Factorial - Editor
Created: 2020-03-23 10:58:34, Last updated: 2022-04-20 10:33:46

This content is licensed under Creative Commons Attribution/Share-Alike License 3.0 (Unported). That means you may freely redistribute or modify this content under the same license conditions and must attribute the original author by placing a hyperlink from your site to this work https://planetcalc.com/8655/. Also, please do not modify any references to the original work (if any) contained in this content.

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

Factorial

Factorial n!

URL copied to clipboard
PLANETCALC, Tips and tricks #12: Long (infinite) calculations