Javascript Math: Geometric Series - javascript

I want to create a Roth IRA value calculator. The end result would accept values for annual contribution amount, interest rate, and total number of contribution years.
The calculation—a geometric series—that I need is:
Balance(Y) = P(1 + r)Y + c[ ((1 + r)Y + 1 - (1 + r)) / r ]
FWIW, I'm getting my math information here: http://www.moneychimp.com/articles/finworks/fmbasinv.htm
How would one go about writing this in Javascript? I've been reading about the math functions, but I can't seem to wrap my head around it...

I would definitely read up on JavaScripts operator precedence
A few things to note...
Grouping holds the highest precedence (), NOT with square brakets []
square brackets are for accessing object members and array literals.
There is no operator for exponents in JavaScript use Math.pow(x, n)
For mathematical operations, you MUST use operators 4(x + 1) with throw an
error telling you 4 is not a function. 4 * (x + 1) works.
The following operators are evaluated left-right * / % + - with * / %
holding equal precedence over + -. So mathematical operations are going to behave similar to pemdas.
Another note JavaScript is a dynamic loosely typed language. All numbers are 64-bit floating points, which can yield odd results in some math equations, e.g.
> .1 + .2 = 0.30000000000000004
Another good read

For solving any mathematics series below algorithm can be used. Even for some cases it will not satisfy your expected answer, but it will be correct in some other way.
Steps are as below:
1) Get the difference between the numbers as shown below:
2) Keep making difference until it seems same(difference get 0).
3) Put the same last number which is coming same in that sequence and by adding that difference complete the series by coming up.
<pre>
Examples are as below:
1 2 3 4 5 6 **7**
1 1 1 1 1 **1**
1 4 9 16 25 **36**
3 5 7 9 **11**
2 2 2 **2**
1 8 27 64 125 **216**
7 19 37 61 **91**
12 18 24 **30**
6 6 **6**
0 **0**
</pre>
The same above algorithm is implemented in below js code.
<pre>
//the input
var arr=[1,4,9,16];
var pa6inoArrayMelvo = function(arrr){
var nxtArr=[];
for(i=0;i<arrr.length;i++){
if(arrr[i+1] != undefined){
nxtArr.push(arrr[i+1] -arrr[i]);
}
}
return nxtArr;
}
var keepArray=[];
var keepAlltheArray= function(ar){
var tempArr=[];
keepArray.push(ar);
if(ar.length>1){
tempArr=pa6inoArrayMelvo(ar);
keepAlltheArray(tempArr);
}else{
generateArray(keepArray.length-1);
console.log("ans is:"+keepArray[0]);
}
}
var generateArray=function(idx){
if(keepArray[idx+1]){
var a=keepArray[idx+1];
var b=keepArray[idx];
var ans=a[a.length-1]+b[a.length-1];
keepArray[idx].push(ans);
}else{
var ans=keepArray[idx][keepArray[idx].length-1];
keepArray[idx].push(ans);
}
if(idx>0){
generateArray(idx-1);
}
}
keepAlltheArray(arr);
</pre>

As Yann Chabot said
P*(1 + r)*Y + c(((1 + r)*Y + 1 - (1 + r)) / r)
is the right answer but just as a side note, if you dont have P initialy you should set it to 1 by default.

Related

Recursive Functions Runtime 2^n - 1

I have the following function fn(n).
function fn(n) {
if (n < 0) return 0;
if (n < 2) return n;
return fn(n - 1) + fn(n - 2);
}
I understand how this code works, but don't how to calculate time complexity for it.
Let’s do some examples:
For n = 3, you have 5 function calls. First fn(3), which in turn calls fn(2) and fn(1) and so on.
For n = 4, you have 9 function calls. First fn(4), which in turn calls fn(3) and fn(2) and so on.
Graphical representation of the 2 examples:
The leftmost nodes go down in descending order: fn(4), fn(3), fn(2), fn(1), which means that the height of the tree (or the number of levels) on the tree will be n.
The time complexity of this code is 2^n - 1. Although, if we count all calls will be just 9 calls for n = 4.
And the question is how we get 2^n - 1? I don't understand
One of the ways of calculating recursive algorithm's time complexity is using the Recursion Tree Method. For this particular case, we can write T(n)=T(n-1)+T(n-2)+2*O(1), where O(1) means constant time, since we have two comparison checks of n values using if. The recursion tree would look something like this:
1 n
2 (n-1) (n-2)
4 (n-2) (n-3) (n-3) (n-4)
8 (n-3)(n-4) (n-4)(n-5) (n-4)(n-5) (n-5)(n-6)
...
2^i for i-th level
Total work done will be the sum of all of the work done in each level, so we can write T(n)=1 + 2 + 4 + 8 + 16 + 32 + ... = 2^0 + 2^1 + 2^2 + 2^3 + 2^4 + ... + 2^i. This is a geometric series which means that the T(n) is equal to (1-2^n)/(1-2) = (1-2^n)/(-1) = 2^n - 1. Because of that the time complexity of the function fn(n) is O(2^n).
You could also approach this using Back Substitution method. We know the following:
T(0)=1
T(1)=1
T(2)=1
T(n)=T(n-1)+T(n-2)+2*O(n)≈2*T(n-1)
Substituting T(n-2) with T(n-1) is allowed. In doing so you will get a higher bound which is still true for T(n-1)+T(n-2).
After the substitution you can also write T(n-1)=2*T(n-2), T(n-2)=2*T(n-3), ...
Using these values and substituting them recursively in to the T(n) you will get:
T(n)=2*2*T(n-2)
=2*2*2*T(n-3)
=2*2*2*2*T(n-4)
=...
=2^i * T(n-i)
From there you can write n-i=1 => i=n-1 and substitute the i value in T(n). You can do this because T(1)=1 is one of the base conditions.
=> T(i)=2^(n-1) * T(n-(n-1))=2^(n-1) * T(n-n+1)=2^(n-1) * T(1)=2^(n-1)
This means that the time complexity is O(2^n).

Can I represent large integers in Node 6 for only exponentiation without a dependency?

I am working on a kata that asks for the last digit of a[0] ^ (a[1] ^ (a[2] ^ ... (a[n-1] ^ a[n]))). When computing the answer, eventually Math.pow exceeds Number.MAX_SAFE_INTEGER, causing modexp below to return erroneous results.
#user2357112 says that JS needs a library for arbitrary-precision integers, which is all well and good, but nothing in the kata indicates that such a library is available in the remote environment, or even that I need one.
Since the kata and SO point in different directions on this matter, I want to learn if I can feasibly represent big integers ONLY for the purposes of solving this kata without writing an entire library.
My in-progress code is below, and it passes many tests before printing incorrect results. Some code was omitted to avoid spoilers.
TL;DR: If I cannot use a library, what can I do to feasibly represent large integers for the use case indicated by Math.pow()?
function modexp(b, e) {
let c = 1
while(e) {
if (e & 1)
c = c * b % 10
e >>= 1
b = b * b % 10
}
return c;
}
function lastDigit(as) {
if (!as || !as.length) return 1;
let e = as.slice(1).reverse().reduce((p,c) => Math.pow(c,p));
return modexp(as[0], Number(e));
}
This is obviously an X-Y problem. You don't need large integers.
You need to go back to elementary school math.
What's multiplication? Well let's take one example:
WARNING: SPOILERS! Don't read the following if you want to figure it out yourself!
1 2
x 2 3
------
3 6 last digit 6
2 4
------
2 7 6 notice how last digit is only involved
in ONE multiplication operation?
Hmm.. there seems to be a pattern. Let's see if that pattern holds. Let's multiply 12 x 23 x 23 by only doing the last digit:
1 2
x 2 3
------
6 calculate ONLY last digit
x 2 3
------
8 answer is: last digit is 8
Let's check our answer:
1 2
x 2 3
------
3 6
2 4
------
2 7 6
x 2 3
------
8 2 8
5 5 2
-------
6 3 4 8 last digit is INDEED 8
So it seems that you can find the last digit by only calculating the last digit. Let's try to implement a powLastDigit() function.
WARNING: SPOILERS! DON'T READ THE CODE IF YOU WANT TO WRITE IT YOURSELF!
function powLastDigit (number,power) {
var x = number;
for (var y=1; y<power; y++) {
x = ((x%10)*(number%10))%10; // we only care about last digit!
}
return x;
}
Let's check if we are right:
> powLastDigit(3,7)
7
> Math.pow(3,7)
2187
> powLastDigit(5,8)
5
> Math.pow(5,8)
390625
> powLastDigit(7,12)
1
> Math.pow(7,12)
13841287201
OK. Looks like it's working. Now you can use this function to solve your problem. It has no issues with very large exponents because it doesn't deal with large numbers:
> powLastDigit(2323,123456789)
3
Optimization
The above code is slow because it uses a loop. It's possible to speed it up by using Math.pow() instead. I'll leave that as a homework problem.
I use bit array to represent a positive integer;
[0,0,1,1] // bit array of 12 (MSB=rightmost)
This structure is used to manipulate the overall exponent, E
a[1] ^ (a[2] .. (a[n-1] ^ a[n])) // E
(!)There is a relation between LSD(a[0]) and the overall exponent E as below
//LSD(a[0]) LSD(LSD(a[0]) ^ E) for
// [E/4R0, E/4R1, E/4R2, E/4R3]
//--------- ----------------------------
// 0 [0, 0, 0, 0]
// 1 [1, 1, 1, 1]
// 2 [6, 2, 4, 8]
// 3 [1, 3, 9, 7]
// 4 [6, 4, 6, 4]
// 5 [5, 5, 5, 5]
// 6 [6, 6, 6, 6]
// 7 [1, 7, 9, 3]
// 8 [6, 8, 4, 2]
// 9 [1, 9, 1, 9]
For example, find least significant digit of (2 ^ (2 ^ 3)),
// LSD(a[0]) is 2
// E is 8
// implies E mod 4 is 0
// LSD(LSD(a[0]) ^ E)
// for E/4R0 is 6 (ans)
To determine E mod 4,
E[0] + E[1] * 2 // the two LSBs
To summarize, I create a data structure, bit array, to store large integers,
mainly for the intermediate value of exponent-part. The bit array is dynamic length obtaining max. 9007199254740991 bits, if all bits are set, the value in decimal is 2 ^ (9007199254740991 + 1) - 1. This bit array will never be converted back to decimal(safe). The only interesting information of overall exponent, E, is its two least significant bits, they are the remainder of E/4
which can be applied to the above relation(!).
Obviously, Math.pow will not work for bit array, so I handcraft a simple exp() for it. This is trivial since the fact that
//exponentiation == lots of multiplications == lots of additions
//it is not difficult to implement addition on bit array
This is the fiddle demonstrating above idea ONLY. It is intended to be slow if the E is really large. FYI
LSD.find([3,4,5,6]) // my Nightly hanged ~3s to find lsd
You may optimize the Bits.exp by means of childprocesses, web workers, debounce function, simd etc. Good luck.
You don't really need a bigint library to solve this kata.
You are only interested in the last digit of the result, and fortunately there is a property of powers that helps us with this. We effectively want to compute a power in modulus 10. Yes, modular exponentiation does help us a bit here, but the problem is that the exponent is very large as well - too large to compute, and too large to run a loop with that many iterations. But we don't need to, all we are interested in is the modulus of the result.
And there is a pattern! Let's take 4x as an example:
x 4^x (4^x)%10
--------------------------
0 4^0 = 1 1
1 4^1 = 4 4
2 4^2 = 16 6
3 4^3 = 64 4
4 4^4 = 256 6
5 4^5 = 1024 4
… …
20 4^20 = ??? 6 sic!
21 4^21 = ??? 4
… …
You will be able to find these patterns for all numbers in all modular bases. They all share the same characteristic: there's a threshold below which the remainder is irregular, and then they form a repeating sequence. To get a number in this sequence, we only need to perform a modulo operation on the exponent!
For the example above ((4^x)%10), we use a lookup table 0 → 6, 1 → 4 and compute x % 2; the threshold is 1. In JavaScript code, it might look like this:
x < 1 ? 1 : [6, 4][x % 2];
Of course, x is a very large number formed by the repeated exponentiation of the rest of the input, but we do not need to compute it as whole - we only want to know
whether it is smaller than a relatively small number (trivial)
what the remainder after division by q is - just a recursive call to the function we're implementing!

Decomposing a value into results of powers of two

Is it possible to get the integers that, being results of powers of two, forms a value?
Example:
129 resolves [1, 128]
77 resolves [1, 4, 8, 64]
I already thought about using Math.log and doing also a foreach with a bitwise comparator. Is any other more beautiful solution?
The easiest way is to use a single bit value, starting with 1 and shift that bit 'left' until its value is greater than the value to check, comparing each bit step bitwise with the value. The bits that are set can be stored in an array.
function GetBits(value) {
var b = 1;
var res = [];
while (b <= value) {
if (b & value) res.push(b);
b <<= 1;
}
return res;
}
console.log(GetBits(129));
console.log(GetBits(77));
console.log(GetBits(255));
Since shifting the bit can be seen as a power of 2, you can push the current bit value directly into the result array.
Example
You can adapt solutions from other languages to javascript. In this SO question you'll find some ways of solving the problem using Java (you can choose the one you find more elegant).
decomposing a value into powers of two
I adapted one of those answers to javascript and come up with this code:
var powers = [], power = 0, n = 129;// Gives [1,128] as output.
while (n != 0) {
if ((n & 1) != 0) {
powers.push(1 << power);
}
++power;
n >>>= 1;
}
console.log(powers);
Fiddle
Find the largest power of two contained in the number.
Subtract from the original number and Add it to list.
Decrement the exponent and check if new 2's power is less than the number.
If less then subtract it from the original number and add it to list.
Otherwise go to step 3.
Exit when your number comes to 0.
I am thinking of creating a list of all power of 2 numbers <= your number, then use an addition- subtraction algorithm to find out the group of correct numbers.
For example number 77:
the group of factors is { 1,2,4,8,16,32,64} [ 64 is the greatest power of 2 less than or equal 77]
An algorithm that continuously subtract the greatest number less than or equal to your number from the group you just created, until you get zero.
77-64 = 13 ==> [64]
13-8 = 7 ==> [8]
7-4 = 3 ==> [4]
3-2 = 1 ==> [2]
1-1 = 0 ==> [1]
Hope you understand my algorithm, pardo my bad english.
function getBits(val, factor) {
factor = factor || 1;
if(val) {
return (val % 2 ? [factor] : []).concat(getBits(val>>1, factor*2))
}
return [];
}
alert(getBits(77));

Generate a big random float jquery/JavaScript [duplicate]

This question already has answers here:
How to deal with big numbers in javascript [duplicate]
(3 answers)
Closed 8 years ago.
I need to generate a 12 digit and 13 decimals float value like this:
123438767411.238792938
How can I do that in Javascript/Jquery? Is it possible to generate this code using JavaScript?
I was trying like this:
v1 = Math.floor((Math.random()*10000000000)+1);
v2 = Math.floor((Math.random()*100000000)+1);
v = v1.toString() + "." + v2.toString();
But this is not working!
(assuming you mean in the form of a string, not as a number, because IEEE 754 can't have that many significant digits)
must the integer part be 12 digits or can it be 1 or 123? If it can be 12 digits or shorter, then it can be
(Math.floor (Math.random() * Math.pow(10,12))
+ (Math.floor (Math.random() * Math.pow(10,13))
/ Math.pow(10,13)).toString().substring(1))
note that the above could have an issue when the decimal part turns out to be 0, although the chance is really small. (then the .0 part is gone, although we can use a conditional to add it when it is so). Or we can treat the decimal part 123 not as .0000000000123 but as .123 and use:
(Math.floor (Math.random() * Math.pow(10,12))
+ "." + Math.floor (Math.random() * Math.pow(10,13)))
But it depends whether we care about 123 becoming .123 and 1230 also becoming .1230 because if we do care about it, we can say .123 is the same as .1230.
Also, if we want to have the form such as 000042987017.0790946977900 as well, so that it is always 12 digit integer and 13 digit decimal, then either we can do zero padding or use something like this:
sample: http://jsfiddle.net/jL4t4/1/
var i, s = "";
for (i = 0; i < 26; i++) {
s += (i === 12) ? "." : Math.floor(Math.random() * 10);
}

Cross-over two integers bitwise

I'm currently trying to realize a very simple example of genetic algorithms.
At one point, you have to do a "Cross-Over" (biology) with two numbers (parents) to get a "child".
You can find an explanation of Cross-Over here:
How to "crossover" two strings (1234 & abcd -> 12cd & ab34)
(The second illustration, the easier "one-point" Cross-Over is the one I'm trying to do.)
The chromosomes (parents and child) are numbers but the "Cross-Over" will be a bit operation.
I found a solution for one of the "chromosomes", which is the following :
Move the bits X amount to the right (>>> operator )
and then move the bits again X positions but this time to the left (<< operator)
So this would keep the end of one of the chromosomes and fill the beginning with 0s.
But I don't really know how to solve the problem of the other chromosome and then also do the Cross-Over.
(Probably a XOR once I kept the beginning / end of the chromosomes and filled the rest with 0s.)
Or should I even approach this problem from another angle?
If the fraction of the Cross-Over is p (e.g., p = .25), then this should work:
mask1 = ((0xffff >> 16*p) << 16*p)
mask2 = 0xffff ^ mask1
output1 = (input1 & mask1) ^ (input2 & mask2)
output2 = (input1 & mask2) ^ (input2 & mask1)
A couple of notes:
This is just pseudocode. You might want some casts in there.
This treats p differently than you treat it in your comment above. (Just replace p with 1-p to get to your definition of p.)
A naive approach would be to use 4 local variables:
int chromatid1Start;
int chromatid1End;
int chromatid2Start;
int chromatid2End;
Then, assign the incoming chromatid1 to the first two variables and chromatid2 to the last two variables.
chromatid1Start = chromatid1;
chromatid1End = chromatid1;
chromatid2Start = chromatid2;
chromatid2End = chromatid2;
Perform a right-shift on the Start chromatid variables up to the crossover point, then left-shift the exact same amount. On the End chromatid variables, left-shift up to the crossover point, then right-shift the exact same amount.
chromatid1Start = (chromatid1Start >> 16 * crossoverPercent) << 16 * crossoverPercent;
chromatid1End = (chromatid1End << 16 * (1 - crossoverPercent)) >> 16 * (1 - crossoverPercent);
chromatid2Start = (chromatid2Start >> 16 * crossoverPercent) << 16 * crossoverPercent;
chromatid2End = (chromatid2End << 16 * (1 - crossoverPercent)) >> 16 * (1 - crossoverPercent);
With that, you can cross the start of one with the end of the other:
int daughterChromatid1 = chromatid1Start + chromatid2End;
int daughterChromatid2 = chromatid2Start + chromatid1End;

Categories