Let's say i have 3 sets of numbers and i want the % of their difference.
30 - 60
94 - 67
10 - 14
I want a function that calculate the percentage of the difference between each 2 numbers, and the most important is to support positive and negative percentages.
Example:
30 - 60 : +100%
94 - 67 : -36% ( just guessing )
10 - 14 : +40%
Thanks
This is pretty basic math.
% difference from x to y is 100*(y-x)/x
The important issue here is whether one of your numbers is a known reference, for example, a theoretical value.
With no reference number, use the percent difference as
100*(y-x)/((x+y)/2)
The important distinction here is dividing by the average, which symmetrizes the definition.
From your example though, it seems that you might want percent error, that is, you are thinking of your first number as the reference number and want to know how the other deviates from that. Then the equation, where x is reference number, is:
100*(y-x)/x
See, e.g., wikipedia, for a small discussion on this.
for x - y the percentage is (y-x)/x*100
Simple math:
function differenceAsPercent($number1, $number2) {
return number_format(($number2 - $number1) / $number1 * 100, 2);
}
echo differenceAsPercent(30, 60); // 100
echo differenceAsPercent(94, 67); // -28.72
echo differenceAsPercent(10, 14); // 40
If the percentage is needed for a voting system then Andrey Korolyov is the only who answered correctly.
Example
10 votes for 1 vote against = 90%
10 votes for 5 votes against = 50%
10 votes for 3 votes against = 70%
100 votes for 1 vote against = 99%
1000 votes for 1 vote against = 99.9%
1 votes for 10 vote against = -90%
5 votes for 10 votes against = -50%
3 votes for 10 votes against = -70%
1 votes for 100 vote against = -99%
1 votes for 1000 vote against = -99.9%
function perc(a,b){
console.log( (a > b) ? (a-b)/a*100 : (b - a)/b*-100);
}
$c = ($a > $b) ? ($a-$b)/$a*-100 : ($b-$a)/$b*100;
In Ukraine children learn these math calculations at the age of 12 :)
Related
Problem:
Fuel Injection Perfection
Commander Lambda has asked for your help to refine the automatic quantum antimatter fuel injection system for her LAMBCHOP doomsday device. It's a great chance for you to get a closer look at the LAMBCHOP - and maybe sneak in a bit of sabotage while you're at it - so you took the job gladly.
Quantum antimatter fuel comes in small pellets, which is convenient since the many moving parts of the LAMBCHOP each need to be fed fuel one pellet at a time. However, minions dump pellets in bulk into the fuel intake. You need to figure out the most efficient way to sort and shift the pellets down to a single pellet at a time.
The fuel control mechanisms have three operations:
Add one fuel pellet Remove one fuel pellet Divide the entire group of fuel pellets by 2 (due to the destructive energy released when a quantum antimatter pellet is cut in half, the safety controls will only allow this to happen if there is an even number of pellets) Write a function called solution(n) which takes a positive integer as a string and returns the minimum number of operations needed to transform the number of pellets to 1. The fuel intake control panel can only display a number up to 309 digits long, so there won't ever be more pellets than you can express in that many digits.
For example: solution(4) returns 2: 4 -> 2 -> 1 solution(15) returns 5: 15 -> 16 -> 8 -> 4 -> 2 -> 1
Test cases
Inputs: (string) n = "4" Output: (int) 2
Inputs: (string) n = "15" Output: (int) 5
my code:
def solution(n):
n = int(n)
if n == 2:
return 1
if n % 2 != 0:
return min(solution(n + 1), solution(n - 1)) + 1
else:
return solution(int(n / 2)) + 1
This is the solution that I came up with with passes 4 out of 10 of the test cases. It seems to be working fine so im wondering if it is because of the extensive runtime. I thought of applying memoization but im not sure how to do it(or if it is even possible). Any help would be greatly appreciated :)
There are several issues to consider:
First, you don't handle the n == "1" case properly (operations = 0).
Next, by default, Python has a limit of 1000 recursions. If we compute the log2 of a 309 digit number, we expect to make a minimum of 1025 divisions to reach 1. And if each of those returns an odd result, we'd need to triple that to 3075 recursive operations. So, we need to bump up Python's recursion limit.
Finally, for each of those divisions that does return an odd value, we'll be spawning two recursive division trees (+1 and -1). These trees will not only increase the number of recursions, but can also be highly redundant. Which is where memoization comes in:
import sys
from functools import lru_cache
sys.setrecursionlimit(3333) # estimated by trial and error
#lru_cache()
def solution(n):
n = int(n)
if n <= 2:
return n - 1
if n % 2 == 0:
return solution(n // 2) + 1
return min(solution(n + 1), solution(n - 1)) + 1
print(solution("4"))
print(solution("15"))
print(solution(str(10**309 - 1)))
OUTPUT
> time python3 test.py
2
5
1278
0.043u 0.010s 0:00.05 100.0% 0+0k 0+0io 0pf+0w
>
So, bottom line is handle "1", increase your recursion limit, and add memoization. Then you should be able to solve this problem easily.
There are more memory- and runtime-efficient ways to solve the problem, which is what Google is testing for with their constraints. Every time you recurse a function, you put another call on the stack, or 2 calls when you recurse twice on each function call. While they seem basic, a while loop was a lot faster for me.
Think of the number in binary - when ever you have a streak of 1s >1 in length at LSB side of the number, it makes sense to add 1 (which will flip that streak to all 0s but add another bit to the overall length), then shift right until you find another 1 in the LSB position. You can solve it in a fixed memory block in O(n) using just a while loop.
If you don't want or can't use functools, you can build your own cache this way :
cache = {}
def solution_rec(n):
n = int(n)
if n in cache:
return cache[n]
else:
if n <= 1:
return 0
if n == 2:
return 1
if n % 2 == 0:
div = n / 2
cache[div] = solution(div)
return cache[div] + 1
else:
plus = n + 1
minus = n - 1
cache[plus] = solution(n + 1)
cache[minus] = solution(n - 1)
return min(cache[plus], cache[minus]) + 1
However, even if it runs much faster and has less recursive calls, it's still too much recursive calls for Python default configuration if you test the 309 digits limit.
it works if you set sys.setrecursionlimit to 1562.
An implementation of #rreagan3's solution, with the exception that an input of 3 should lead to a subtraction rather than an addition even through 3 has a streak of 1's on the LSB side:
def solution(n):
n = int(n)
count = 0
while n > 1:
if n & 1 == 0:
n >>= 1
elif n & 2 and n != 3:
n += 1
else:
n -= 1 # can also be: n &= -2
count += 1
return count
Demo: https://replit.com/#blhsing/SlateblueVeneratedFactor
The problem is how do we compute the integer value of floor(log2(5^x)) without floating point arithmetic or long integer computation? I'm looking for a simple, efficient and mathematically elegant way.
Observations:
The formula is just the number of bits in 5**x (plus 1)
Attempts:
I tried to simplify it to:
floor(x*log2(5))
In my use case, x is not extremely large, probably just 1-100. While an elegant formula that works for small values would suffice me, I would be interested in a formula/algorithm that works for any value of x
I'm making a reference software implementation of universal numbers (type III). I want to make everything easily convertible to microcode by purely using bitwise and basic operations. This is one of the formulas i need to simplify.
As you correctly note, log2(5**x) == x * log2(5). log2(5) is a constant, which can be approximated to 2.3219281.
However, floats aren't allowed per the question. Not an issue!
log2_5 = 23219281;
scale = 10000000; // note log2_5/scale is the actual value
result = x * log2_5;
output = (result - (result % scale)) / scale;
By reducing result by result % scale, dividing it by scale will be an integer division, not a float.
for a simple, efficient and mathematically elegant way... floor(x*log2(5))
Since x has integer values 1 to 100, various tests can to made to find the "best" that uses an integer multiply and a divide by power_of_2.
f(x) = x*a integer_divide power_of_2
For
f(x) = floor(x*log2(5)) = floor(x*some_float_c) the value of some_float_c is bounded by 100 minimum and maximums below.
x f(x) mn mx
f(x)/x (f(x) + 1)/x
1 2 2.00000 3.00000
2 4 2.00000 2.50000
3 6 2.00000 2.33333
...
59 136 2.30508 2.32203
...
87 202 2.32184 2.33333
...
98 227 2.31633 2.32653
99 229 2.31313 2.32323
100 232 2.32000 2.33000
The maximum min is 2.32184 and the minimum max is 2.32203, :
2.32184... <= some_float_c < 2.32203...
Since we cannot use float, find some_integer/some_power_of_2
2.32184... <= some_integer/some_power_of_2 < 2.32203...
ceil(some_power_of_2 * 2.32184...) <= some_integer < floor(some_power_of_2 * 2.32203...)
min max
2.32184 2.32203
2 5 4
4 10 9
8 19 18
...
1024 2378 2377
2048 4756 4755
4096 9511 9511 < first one where min <= max
8192 19021 19022
So 9511/4096 is the "simplest" and is a "best" candidate.
f(x) = (x*9511) integer_divide_by_power_of_2 4096
// In C
unsigned y = (x*9511u) >> 12;
Here is a very rough approximation, but it can help if you want to obtain it mentally
5^3 = 125
2^7 = 128
So for raising to the power of n:
5^n ~~ 2^(7n/3)
So 5^12 is near 2^28 might require up to 29 bits.
It's a bit overestimated because 2^7 > 5^3, so 28 bits are enough, a good usage is to simply round the fraction upper.
If I evaluate in Smalltalk:
(1 to: 50) reject: [:i | (5 raisedTo: i) highBit = (i*7/3) ceiling].
I get:
#(31 34 37 40 43 46 49)
You see that the very simple formulation works up to 5^30 which is not that bad.
e.g. given the following number modulo 55
74627282173621618272362 % 55 = 47
why does splitting the number; calculate first part modulo 55; add result in front of the second part and use modulo 55 again; yield the same result again?
using the example above:
746272821736 % 55 = 46
'46' + '21618272362' = 4621618272362
4621618272362 % 55 = 47
same result if you calculate the number digit by digit using the way described above
7 % 55 = 7
'7' + '4' = 74 % 55 = 19
'19' + '6' = 196 % 55 = 31
'31' + '2' = 312 % 55 = 37
....
result = 47
could someone clarify WHY?
It comes so because the property which holds here is basic and is
Dividend = Divisor * Quotient + Remainder
This is all because of long-division method.
I am working out a question for you.
Ex :- 123456789 % 4
Here,
55 ) 123456789 ( 22...
-110_______
13456789 // here, you'd have replaced it as 13456789 which indeed comes from long-division
-110_____
2456789 // here, you'd have replaced it as 2456789 which indeed comes from long-division
It is so because the remainders are itself put down in the
long-division method exactly below the number so that the number gets
reduced and the number in next stage is substituted by remainder left
appended next by the rest-undivided number.
What you're quoting is none-different from this case.
So,you see that once you find a number which yields remainder 0 in
between, you can drop the digits upto which your remainder is 0.
And,then fresh start with the further digits assuming it as the given
number. This is surely a formula-type thing.
But,your hypothesis was correct and is what we use in the long-division method of formulating the remainders/modulo!
This should be simple enough but the maths for this eludes me. I am looking to express this in C++ but some psuedo code will happily do, or just the maths really.
The function will be given a number of a container and it will return the number of items in that container. The number of items is based on their number and halves at certain number height.
The first halving is at number 43,200 and then every time after it is the gap number of containers between the previous halving plus 43,200
It may sounds confusing, it will look like the following.
1 to 43200 = 512
43201 to 86400 = 256
86401 to 129600 = 128
129601 to 172800 = 64
172801 to 216000 = 32
216001 to 259200 = 16
and so
So if a number up to 43,200 is given the result is 512, the number 130,000 will return 64. The value can be less than 1 taking up several decimal places.
global halvingInterval = 43200
global startingInventory = 512
def boxInventory(boxNumber):
currentInventory = startingInventory
while(boxNumber > halvingInterval):
currentInventory = currentInventory/2
boxNumber -= halvingInterval
return currentInventory
This code will take the box number. It will keep subtracting the halving interval until you get to the right inventory area, and then return the inventory when it is done.
N = (noitems + 1) / 43200;
L2 = log(512) / log(2);
answer = exp( log(2) * (1 + L2 - N) );
I have been trying to get my head around this perticular complexity computation but everything i read about this type of complexity says to me that it is of type big O(2^n) but if i add a counter to the code and check how many times it iterates per given n it seems to follow the curve of 4^n instead. Maybe i just misunderstood as i placed an count++; inside the scope.
Is this not of type big O(2^n)?
public int test(int n)
{
if (n == 0)
return 0;
else
return test(n-1) + test(n-1);
}
I would appreciate any hints or explanation on this! I completely new to this complexity calculation and this one has thrown me off the track.
//Regards
int test(int n)
{
printf("%d\n", n);
if (n == 0) {
return 0;
}
else {
return test(n - 1) + test(n - 1);
}
}
With a printout at the top of the function, running test(8) and counting the number of times each n is printed yields this output, which clearly shows 2n growth.
$ ./test | sort | uniq -c
256 0
128 1
64 2
32 3
16 4
8 5
4 6
2 7
1 8
(uniq -c counts the number of times each line occurs. 0 is printed 256 times, 1 128 times, etc.)
Perhaps you mean you got a result of O(2n+1), rather than O(4n)? If you add up all of these numbers you'll get 511, which for n=8 is 2n+1-1.
If that's what you meant, then that's fine. O(2n+1) = O(2⋅2n) = O(2n)
First off: the 'else' statement is obsolete since the if already returns if it evaluates to true.
On topic: every iteration forks 2 different iterations, which fork 2 iterations themselves, etc. etc. As such, for n=1 the function is called 2 times, plus the originating call. For n=2 it is called 4+1 times, then 8+1, then 16+1 etc. The complexity is therefore clearly 2^n, since the constant is cancelled out by the exponential.
I suspect your counter wasn't properly reset between calls.
Let x(n) be a number of total calls of test.
x(0) = 1
x(n) = 2 * x(n - 1) = 2 * 2 * x(n-2) = 2 * 2 * ... * 2
There is total of n twos - hence 2^n calls.
The complexity T(n) of this function can be easily shown to equal c + 2*T(n-1). The recurrence given by
T(0) = 0
T(n) = c + 2*T(n-1)
Has as its solution c*(2^n - 1), or something like that. It's O(2^n).
Now, if you take the input size of your function to be m = lg n, as might be acceptable in this scenario (the number of bits to represent n, the true input size) then this is, in fact, an O(m^4) algorithm... since O(n^2) = O(m^4).