Is there a more elegant way to calculate x = (y / n) + (y % n ? 1 : 0) ? - math

While programming I often find myself needing to calculate something like:
x = (y / n) + (y % n ? 1 : 0);
Or more explicitly:
x = y / n;
if (y % n != 0) {
x = x + 1;
}
Is there a more elegant way to achieve this value? Can it be achieved without using a conditional expression?

So, you want the integer division to round up instead of down. You can fake this by adding n-1 to the numerator:
x = (y + n - 1) / n;
That way you shift the value it'll be rounded down to just enough to give you the desired outcome.

Related

Prove recursion: Show that M(n) >= 1/2 (n + 1) lg(n + 1)

I want to show that the recursion of quicksort run on best time time on n log n.
i got this recursion formula
M(0) = 1
M(1) = 1
M(n) = min (0 <= k <= n-1) {M(K) + M(n - k - 1)} + n
show that M(n) >= 1/2 (n + 1) lg(n + 1)
what i have got so far:
By induction hyposes
M(n) <= min {M(k) + M(n - k - 1} + n
focusing on the inner expresison i got:
1/2(k + 1)lg(k + 1) + 1/2(n - k)lg(n - k)
1/2lg(k + 1)^(k + 1) + 1/2lg(n - k)^(n - k)
1/2(lg(k + 1)^(k + 1) + lg(n - k)^(n - k)
1/2(lg((k + 1)^(k + 1) . (n - k)^(n - k))
But i think im doing something wrong. i think the "k" should be gonne but i cant see how this equation would cancel out all the "k". So, probably, im doing something wrong
You indeed want to get rid of k. To do this, you want to find the lower bound on the minimum of M(k) + M(n - k - 1). In general it can be arbitrarily tricky, but in this case the standard approach works: take derivative by k.
((k+1) ln(k+1) + (n-k) ln(n-k))' =
ln(k+1) + (k+1)/(k+1) - ln(n-k) - (n-k)/(n-k) =
ln((k+1) / (n-k))
We want the derivative to be 0, so
ln((k+1) / (n-k)) = 0 <=>
(k+1) / (n-k) = 1 <=>
k + 1 = n - k <=>
k = (n-1) / 2
You can check that it's indeed a local minimum.
Therefore, the best lower bound on M(k) + M(n - k - 1) (which we can get from the inductive hypothesis) is reached for k=(n-1)/2. Now you can just substitute this value instead of k, and n will be your only remaining variable.

How to solve z = (((m / k) / j) / x) for x optimizing z towards 2ˣ

So say I have these variables:
m is the amount of memory available in bits
k is a dividing factor
j is another dividing factor, kept as a separate variable instead of combining with k
x is the value we want to figure out.
z is the value we want to be a closest to 2^x
Then we have
let z = (((m / k) / j) / x)
So for example, say we have this:
m = 2000000
k = 5
j = 10
x = ?
z = ?
Then we have
let z = ((2000000 / 5) / 10) / x
I would like to figure out what x is given that z should be as close to 2 to the power of x as possible. The way I am currently doing this is by just plugging in numbers and trying to get them close to matching. But I'm wondering a generic way to programmatically solve this. But for example, I might try plugging in x = 10, which equals:
4000 = ((2000000 / 5) / 10) / 10
Then 2¹⁰ = 1024 which is decently close to 4000, but I don't know what would be closer. Trying x = 11 gives:
3636 = ((2000000 / 5) / 10) / 11
And 2¹¹ = 2048, so x = 11 is a better solution.
Wondering how I can programmatically solve this. I have tried to factor the equation out, but it's been a while since I've done this so I don't know.
z = (((m / k) / j) / x)
x * z = (m / k) / j
j * (x * z) = m / k
k * (j * (x * z)) = m
...
A bit lost now, not sure how to get it to the point of this:
f(k, j) = ... => [ x, z ]
Generally I'm trying to figure out how to solve an equation programmatically. Just seeing an implementation would allow me to understand without making it too broad.
What I've been doing currently is basically going into the debugger and typing in some JavaScript to find values, but there's gotta be a better way.
You can do an iterative search:
x = 1
best_error = infinity
best_x = 0
while True:
z = (((m / k) / j) / x)
error = abs(z - pow(2,x))
if error > best_error
return best_x
best_error = error
best_x = x
x = x+1
For other relationships there are better ways of choosing the next x, but for this particular problem a linear search seems fine.

Converting matlab code to R code

I was wondering how I can convert this code from Matlab to R code. It seems this is the code for midpoint method. Any help would be highly appreciated.
% Usage: [y t] = midpoint(f,a,b,ya,n) or y = midpoint(f,a,b,ya,n)
% Midpoint method for initial value problems
%
% Input:
% f - Matlab inline function f(t,y)
% a,b - interval
% ya - initial condition
% n - number of subintervals (panels)
%
% Output:
% y - computed solution
% t - time steps
%
% Examples:
% [y t]=midpoint(#myfunc,0,1,1,10); here 'myfunc' is a user-defined function in M-file
% y=midpoint(inline('sin(y*t)','t','y'),0,1,1,10);
% f=inline('sin(y(1))-cos(y(2))','t','y');
% y=midpoint(f,0,1,1,10);
function [y t] = midpoint(f,a,b,ya,n)
h = (b - a) / n;
halfh = h / 2;
y(1,:) = ya;
t(1) = a;
for i = 1 : n
t(i+1) = t(i) + h;
z = y(i,:) + halfh * f(t(i),y(i,:));
y(i+1,:) = y(i,:) + h * f(t(i)+halfh,z);
end;
I have the R code for Euler method which is
euler <- function(f, h = 1e-7, x0, y0, xfinal) {
N = (xfinal - x0) / h
x = y = numeric(N + 1)
x[1] = x0; y[1] = y0
i = 1
while (i <= N) {
x[i + 1] = x[i] + h
y[i + 1] = y[i] + h * f(x[i], y[i])
i = i + 1
}
return (data.frame(X = x, Y = y))
}
so based on the matlab code, do I need to change h in euler method (R code) to (b - a) / n to modify Euler code to midpoint method?
Note
Broadly speaking, I agree with the expressed comments; however, I decided to vote up this question. (now deleted) This is due to the existence of matconv that facilitates this process.
Answer
Given your code, we could use matconv in the following manner:
pacman::p_load(matconv)
out <- mat2r(inMat = "input.m")
The created out object will attempt to translate Matlab code into R, however, the job is far from finished. If you inspect the out object you will see that it requires further work. Simple statements are usually translated correctly with Matlab comments % replaced with # and so forth but more complex statements may require a more detailed investigation. You could then inspect respective line and attempt to evaluate them to see where further work may be required, example:
eval(parse(text=out$rCode[1]))
NULL
(first line is a comment so the output is NULL)

Math Problem: Scale a graph so that it matches another

I have 2 tables of values and want to scale the first one so that it matches the 2nd one as good as possible. Both have the same length. If both are drawn as graphs in a diagram they should be as close to each other as possible. But I do not want quadratic, but simple linear weights.
My problem is, that I have no idea how to actually compute the best scaling factor because of the Abs function.
Some pseudocode:
//given:
float[] table1= ...;
float[] table2= ...;
//wanted:
float factor= ???; // I have no idea how to compute this
float remainingDifference=0;
for(int i=0; i<length; i++)
{
float scaledValue=table1[i] * factor;
//Sum up the differences. I use the Abs function because negative differences are differences too.
remainingDifference += Abs(scaledValue - table2[i]);
}
I want to compute the scaling factor so that the remainingDifference is minimal.
Simple linear weights is hard like you said.
a_n = first sequence
b_n = second sequence
c = scaling factor
Your residual function is (sums are from i=1 to N, the number of points):
SUM( |a_i - c*b_i| )
Taking the derivative with respect to c yields:
d/dc SUM( |a_i - c*b_i| )
= SUM( b_i * (a_i - c*b_i)/|a_i - c*b_i| )
Setting to 0 and solving for c is hard. I don't think there's an analytic way of doing that. You may want to try https://math.stackexchange.com/ to see if they have any bright ideas.
However if you work with quadratic weights, it becomes significantly simpler:
d/dc SUM( (a_i - c*b_i)^2 )
= SUM( 2*(a_i - c*b_i)* -c )
= -2c * SUM( a_i - c*b_i ) = 0
=> SUM(a_i) - c*SUM(b_i) = 0
=> c = SUM(a_i) / SUM(b_i)
I strongly suggest the latter approach if you can.
I would suggest trying some sort of variant on Newton Raphson.
Construct a function Diff(k) that looks at the difference in area between your two graphs between fixed markers A and B.
mathematically I guess it would be integral ( x = A to B ){ f(x) - k * g(x) }dx
anyway realistically you could just subtract the values,
like if you range from X = -10 to 10, and you have a data point for f(i) and g(i) on each integer i in [-10, 10], (ie 21 datapoints )
then you just sum( i = -10 to 10 ){ f(i) - k * g(i) }
basically you would expect this function to look like a parabola -- there will be an optimum k, and deviating slightly from it in either direction will increase the overall area difference
and the bigger the difference, you would expect the bigger the gap
so, this should be a pretty smooth function ( if you have a lot of data points )
so you want to minimise Diff(k)
so you want to find whether derivative ie d/dk Diff(k) = 0
so just do Newton Raphson on this new function D'(k)
kick it off at k=1 and it should zone in on a solution pretty fast
that's probably going to give you an optimal computation time
if you want something simpler, just start with some k1 and k2 that are either side of 0
so say Diff(1.5) = -3 and Diff(2.9) = 7
so then you would pick a k say 3/10 of the way (10 = 7 - -3) between 1.5 and 2.9
and depending on whether that yields a positive or negative value, use it as the new k1 or k2, rinse and repeat
In case anyone stumbles upon this in the future, here is some code (c++)
The trick is to first sort the samples by the scaling factor that would result in the best fit for the 2 samples each. Then start at both ends iterate to the factor that results in the minimum absolute deviation (L1-norm).
Everything except for the sort has a linear run time => Runtime is O(n*log n)
/*
* Find x so that the sum over std::abs(pA[i]-pB[i]*x) from i=0 to (n-1) is minimal
* Then return x
*/
float linearFit(const float* pA, const float* pB, int n)
{
/*
* Algebraic solution is not possible for the general case
* => iterative algorithm
*/
if (n < 0)
throw "linearFit has invalid argument: expected n >= 0";
if (n == 0)
return 0;//If there is nothing to fit, any factor is a perfect fit (sum is always 0)
if (n == 1)
return pA[0] / pB[0];//return x so that pA[0] = pB[0]*x
//If you don't like this , use a std::vector :P
std::unique_ptr<float[]> targetValues_(new float[n]);
std::unique_ptr<int[]> indices_(new int[n]);
//Get proper pointers:
float* targetValues = targetValues_.get();//The value for x that would cause pA[i] = pB[i]*x
int* indices = indices_.get(); //Indices of useful (not nan and not infinity) target values
//The code above guarantees n > 1, so it is safe to get these pointers:
int m = 0;//Number of useful target values
for (int i = 0; i < n; i++)
{
float a = pA[i];
float b = pB[i];
float targetValue = a / b;
targetValues[i] = targetValue;
if (std::isfinite(targetValue))
{
indices[m++] = i;
}
}
if (m <= 0)
return 0;
if (m == 1)
return targetValues[indices[0]];//If there is only one target value, then it has to be the best one.
//sort the indices by target value
std::sort(indices, indices + m, [&](int ia, int ib){
return targetValues[ia] < targetValues[ib];
});
//Start from the extremes and meet at the optimal solution somewhere in the middle:
int l = 0;
int r = m - 1;
// m >= 2 is guaranteed => l > r
float penaltyFactorL = std::abs(pB[indices[l]]);
float penaltyFactorR = std::abs(pB[indices[r]]);
while (l < r)
{
if (l == r - 1 && penaltyFactorL == penaltyFactorR)
{
break;
}
if (penaltyFactorL < penaltyFactorR)
{
l++;
if (l < r)
{
penaltyFactorL += std::abs(pB[indices[l]]);
}
}
else
{
r--;
if (l < r)
{
penaltyFactorR += std::abs(pB[indices[r]]);
}
}
}
//return the best target value
if (l == r)
return targetValues[indices[l]];
else
return (targetValues[indices[l]] + targetValues[indices[r]])*0.5;
}

Math Mod Containing Numbers

i would like to write a simple line of code, without resorting to if statements, that would evaluate whether a number is within a certain range. i can evaluate from 0 - Max by using the modulus.
30 % 90 = 30 //great
however, if the test number is greater than the maximum, using modulus will simply start it at 0 for the remaining, where as i would like to limit it to the maximum if it's past the maximum
94 % 90 = 4 //i would like answer to be 90
it becomes even more complicated, to me anyway, if i introduce a minimum for the range. for example:
minimum = 10
maximum = 90
therefore, any number i evaluate should be either within range, or the minimum value if it's below range and the maximum value if it's above range
-76 should be 10
2 should be 10
30 should be 30
89 should be 89
98 should be 90
23553 should be 90
is it possible to evaluate this with one line of code without using if statements?
Probably the simplest way is to use whatever max and min are available in your language like this:
max(10, min(number, 90))
In some languages, e.g. Java, JavaScript, and C# (and probably others) max and min are static methods of the Math class.
I've used a clip function to make it easier (this is in JavaScript):
function clip(min, number, max) {
return Math.max(min, Math.min(number, max));
}
simple, but still branches even though if is not used:
r = ( x < minimum ) ? minimum : ( x > maximum ) ? maximum : x;
from bit twiddling hacks, assuming (2<3) == 1:
r = y ^ ((x ^ y) & -(x < y)); // min(x, y)
r = x ^ ((x ^ y) & -(x < y)); // max(x, y)
putting it together, assuming min < max:
r = min^(((max^((x^max)&-(max<x)))^min)&-(x<min));
how it works when x<y:
r = y ^ ((x ^ y) & -(x < y));
r = y ^ ((x ^ y) & -(1)); // x<y == 1
r = y ^ ((x ^ y) & ~0); // -1 == ~0
r = y ^ (x ^ y); // (x^y) & ~0 == (x^y)
r = y ^ x ^ y; // y^y == 0
r = x;
otherwise:
r = y ^ ((x ^ y) & -(x < y));
r = y ^ ((x ^ y) & -(0)); // x<y == 0
r = y ^ ((x ^ y) & 0); // -0 == 0
r = y; // (x^y) & 0 == 0
If you are using a language that has a ternary operator (such as C or Java), you could do it like this:
t < lo ? lo : (t > hi ? hi : t)
where t is the test variable, and lo and hi are the limits. That satisfies your constraints, in that it doesn't strictly use if-statements, but the ternary operator is really just syntactic sugar for an if-statement.
Using C/C++:
value = min*(number < min) +
max*(number > max) +
(number <= max && number >= min)*number%max;
The following is a brief explanation. Note that the code depends on 2 important issues to work correctly. First, in C/C++ a boolean expression can be converted to an integer. Second, the reminder of a negative number is the number it self. So, it is not the mathematical definition of the remainder. I am not sure if this is defined by the C/C++ standards or it is left to the implementation. Basically:
if number < min then:
value = min*1 +
max*0 +
0*number%max;
else if number > max
value = min*0 +
max*1 +
0*number%max;
else
value = min*1 +
max*1 +
1*number%max;
I don't see how you could...
(X / 10) < 1 ? 10 : (X / 90 > 1 ? 90 : X)
Number divided by 10 is less than 1? set to 10
Else
If number divided by 90 is greater than 90, set to 90
Else
set to X
Note that it's still hidden ifs. :(

Resources