How to "absolute-ly" take from a number? (How to offset a number?) - gdscript

Essentially what I need to do is a - b, but I don't know what either will be and if a is positive then how can I take b from a in a "absolute" way?
What I mean is for example A = 10 and B = 5. Answer is obviously 5. If A was now -10, the answer is now -5. The answer leans towards 0 no matter what the numbers are. I heavily want to avoid using an if statement if I can.
My original idea was a - (b * (b / abs(b))). But b can be 0, and then div by 0 error occurs.
EDIT: A better way of saying it is I want to offset the result by an amount instead of math.

So do I understand correctly that whatever the value of A, you want it to bias towards zero (based on the initial value of A) by the value of B?
So given:
A=10 and B=5, the result will be 5.
A=-10 and B=5, the result will be -5.
A=-5 and B=-10, the result will be 5 (because it is offset by 10, towards zero from a starting point of -5).
Effectively the sign of B is immaterial because it specifies an offset towards zero in all cases.
What of the case where A=0 and B is non-zero? Is the result supposed to be undefined (because the appropriate direction of offset cannot be inferred), or is it supposed to be zero?
The formula for the latter case would be (ABS(A) - ABS(B)) * SIGN(A)) (assuming that the sign function returns 0 when A is zero).

Related

Fastest way to check if either one of two numbers is odd using bitwise operations

I came up with the following code (written in Solidity assembly):
let z := xor(and(x, 1), and(y, 1))
Where x and y are of type int256 (they are signed and can have negative values). z is the result, and it's equal to 1 when either of x and y are odd, and 0 when both are either odd or even.
The question is whether there is any algorithm that is faster than the one I wrote above?

Can condition that a*b>a where (a>b) promise computation without overflow?

Problem: given two integers a, b (a>b) and the only data type can be used is int; besides compiler adopt two's complement computation method.
Can ab>a promise the result ab is right without overflow?
If the answer is yes, how can I prove? otherwise, how to find counterexample and what's the right condition?
To answer the question in part, in the C# program
using System;
public class Program
{
public static void Main()
{
int a = 654321;
int b = -654321;
var iBool = a * b > a;
Console.WriteLine(iBool);
}
}
the condition a * b > a evalues to true, which is analytically wrong. b is negative and a is positive, so a*b must be negative, but of larger absolute value than b, which means that a*b cannot be larger than a. However, the implementation decides otherwise.
No.
Let's look at positive numbers first. In order for the promise to be wrong, the overflow must be so large that it not only overflows but is larger than a, so something well in excess of twice INT_MAX would be needed (to be precise it needs to be something larger than abs(INT_MIN)+INT_MAX+a).
Intuitively that looks like it can't happen, but it is not as impossible as it seems because a and b only both need to be significantly larger than one half the bit size of int, but not too close to the maximum.
It's easier to see that the promise doesn't hold with negative a and b. The precondition a > b implies that if a is negative, then b is negative as well, and thus the result of multiplying them is always positive.
Positive numbers are always larger than negative numbers, no matter which numbers you choose, so a*b > a is always true whenever a and b are both negative, you always promise no overflow has happened, regardless of whether that is the case.
Except, well except when a and b are small enough, integer overflow will happen.
Take any two non-special, but decidedly negative integers, say -5'000'000 and -500'000, which fulfill the precondition a > b.
Multiply them and you get 2'500'000'000'000 which is significantly overflowing (several times, actually).
The result is 329033728, which is definitively larger than -5'000'000, so you wrongly promise that no overflow has happened.

What is this code doing? Machine Learning

I'm just learning matlab and I have a snippet of code which I don't understand the syntax of. The x is an n x 1 vector.
Code is below
p = (min(x):(max(x)/300):max(x))';
The p vector is used a few lines later to plot the function
plot(p,pp*model,'r');
It generates an arithmetic progression.
An arithmetic progression is a sequence of numbers where the next number is equal to the previous number plus a constant. In an arithmetic progression, this constant must stay the same value.
In your code,
min(x) is the initial value of the sequence
max(x) / 300 is the increment amount
max(x) is the stopping criteria. When the result of incrementation exceeds this stopping criteria, no more items are generated for the sequence.
I cannot comment on this particular choice of initial value and increment amount, without seeing the surrounding code where it was used.
However, from a naive perspective, MATLAB has a linspace command which does something similar, but not exactly the same.
Certainly looks to me like an odd thing to be doing. Basically, it's creating a vector of values p that range from the smallest to the largest values of x, which is fine, but it's using steps between successive values of max(x)/300.
If min(x)=300 and max(x)=300.5 then this would only give 1 point for p.
On the other hand, if min(x)=-1000 and max(x)=0.3 then p would have thousands of elements.
In fact, it's even worse. If max(x) is negative, then you would get an error as p would start from min(x), some negative number below max(x), and then each element would be smaller than the last.
I think p must be used to create pp or model somehow as well so that the plot works, and without knowing how I can't suggest how to fix this, but I can't think of a good reason why it would be done like this. using linspace(min(x),max(x),300) or setting the step to (max(x)-min(x))/299 would make more sense to me.
This code examines an array named x, and finds its minimum value min(x) and its maximum value max(x). It takes the maximum value and divides it by the constant 300.
It doesn't explicitly name any variable, setting it equal to max(x)/300, but for the sake of explanation, I'm naming it "incr", short for increment.
And, it creates a vector named p. p looks something like this:
p = [min(x), min(x) + incr, min(x) + 2*incr, ..., min(x) + 299*incr, max(x)];

Simplifying a 9 variable boolean expression

I am trying to create a tic-tac-toe program as a mental exercise and I have the board states stored as booleans like so:
http://i.imgur.com/xBiuoAO.png
I would like to simplify this boolean expression...
(a&b&c) | (d&e&f) | (g&h&i) | (a&d&g) | (b&e&h) | (c&f&i) | (a&e&i) | (g&e&c)
My first thoughts were to use a Karnaugh Map but there were no solvers online that supported 9 variables.
and heres the question:
First of all, how would I know if a boolean condition is already as simple as possible?
and second: What is the above boolean condition simplified?
2. Simplified condition:
The original expression
a&b&c|d&e&f|g&h&i|a&d&g|b&e&h|c&f&i|a&e&i|g&e&c
can be simplified to the following, knowing that & is more prioritary than |
e&(d&f|b&h|a&i|g&c)|a&(b&c|d&g)|i&(g&h|c&f)
which is 4 chars shorter, performs in the worst case 18 & and | evaluations (the original one counted 23)
There is no shorter boolean formula (see point below). If you switch to matrices, maybe you can find another solution.
1. Making sure we got the smallest formula
Normally, it is very hard to find the smallest formula. See this recent paper if you are more interested. But in our case, there is a simple proof.
We will reason about a formula being the smallest with respect to the formula size, where for a variable a, size(a)=1, for a boolean operation size(A&B) = size(A|B) = size(A) + 1 + size(B), and for negation size(!A) = size(A) (thus we can suppose that we have Negation Normal Form at no cost).
With respect to that size, our formula has size 37.
The proof that you cannot do better consists in first remarking that there are 8 rows to check, and that there is always a pair of letter distinguishing 2 different rows. Since we can regroup these 8 checks in no less than 3 conjuncts with the remaining variable, the number of variables in the final formula should be at least 8*2+3 = 19, from which we can deduce the minimal tree size.
Detailed proof
Let us suppose that a given formula F is the smallest and in NNF format.
F cannot contain negated variables like !a. For that, remark that F should be monotonic, that is, if it returns "true" (there is a winning row), then changing one of the variables from false to true should not change that result. According to Wikipedia, F can be written without negation. Even better, we can prove that we can remove the negation. Following this answer, we could convert back and from DNF format, removing negated variables in the middle or replacing them by true.
F cannot contain a sub-tree like a disjunction of two variables a|b.
For this formula to be useful and not exchangeable with either a or b, it would mean that there are contradicting assignments such that for example
F[a|b] = true and F[a] = false, therefore that a = false and b = true because of monotonicity. Also, in this case, turning b to false makes the whole formula false because false = F[a] = F[a|false] >= F[a|b](b = false).
Therefore there is a row passing by b which is the cause of the truth, and it cannot go through a, hence for example e = true and h = true.
And the checking of this row passes by the expression a|b for testing b. However, it means that with a,e,h being true and all other set to false, F is still true, which contradicts the purpose of the formula.
Every subtree looking like a&b checks a unique row. So the last letter should appear just above the corresponding disjunction (a&b|...)&{c somewhere for sure here}, or this leaf is useless and either a or b can be removed safely. Indeed, suppose that c does not appear above, and the game is where a&b&c is true and all other variables are false. Then the expression where c is supposed to be above returns false, so a&b will be always useless. So there is a shorter expression by removing a&b.
There are 8 independent branches, so there is at least 8 subtrees of type a&b. We cannot regroup them using a disjunction of 2 conjunctions since a, f and h never share the same rows, so there must be 3 outer variables. 8*2+3 makes 19 variables appear in the final formula.
A tree with 19 variables cannot have less than 18 operators, so in total the size have to be at least 19+18 = 37.
You can have variants of the above formula.
QED.
One option is doing the Karnaugh map manually. Since you have 9 variables, that makes for a 2^4 by 2^5 grid, which is rather large, and by the looks of the equation, probably not very interesting either.
By inspection, it doesn't look like a Karnaugh map will give you any useful information (Karnaugh maps basically reduce expressions such as ((!a)&b) | (a&b) into b), so in that sense of simplification, your expression is already as simple as it can get. But if you want to reduce the number of computations, you can factor out a few variables using the distributivity of the AND operators over ORs.
The best way to think of this is how a person would think of it. No person would say to themselves, "a and b and c, or if d and e and f," etc. They would say "Any three in a row, horizontally, vertically, or diagonally."
Also, instead of doing eight checks (3 rows, 3 columns, and 2 diagonals), you can do just four checks (three rows and one diagonal), then rotate the board 90 degrees, then do the same checks again.
Here's what you end up with. These functions all assume that the board is a three-by-three matrix of booleans, where true represents a winning symbol, and false represents a not-winning symbol.
def win?(board)
winning_row_or_diagonal?(board) ||
winning_row_or_diagonal?(rotate_90(board))
end
def winning_row_or_diagonal?(board)
winning_row?(board) || winning_diagonal?(board)
end
def winning_row?(board)
3.times.any? do |row_number|
three_in_a_row?(board, row_number, 0, 1, 0)
end
end
def winning_diagonal?(board)
three_in_a_row?(board, 0, 0, 1, 1)
end
def three_in_a_row?(board, x, y, delta_x, delta_y)
3.times.all? do |i|
board[x + i * delta_x][y + i * deltay]
end
end
def rotate_90(board)
board.transpose.map(&:reverse)
end
The matrix rotate is from here: https://stackoverflow.com/a/3571501/238886
Although this code is quite a bit more verbose, each function is clear in its intent. Rather than a long boolean expresion, the code now expresses the rules of tic-tac-toe.
You know it's a simple as possible when there are no common sub-terms to extract (e.g. if you had "a&b" in two different trios).
You know your tic tac toe solution must already be as simple as possible because any pair of boxes can belong to at most only one winning line (only one straight line can pass through two given points), so (a & b) can't be reused in any other win you're checking for.
(Also, "simple" can mean a lot of things; specifying what you mean may help you answer your own question. )

Matlab problem with writing equations

i am having problem with writing equations.
r = 25, k= 2, R = 50:25:600, DR = 0.5:0.5:4.0
h= r*[1-cos(asin((sqrt(2*R*DR+DR^2))+r*sin(acos(r-k)/r)/r))]-k
but as a resault i get this: h = 1.9118e+001 +1.7545e+002i.
I just start with Matlab. Thanks
What I get from what you've written is actually
??? Error using ==> mtimes
Inner matrix dimensions must agree.
which is correct because you're trying to multiply two row vectors by one another. Could you please show us the actual code you used?
Anyway, supposing that's dealt with somehow, it looks to me as if you're feeding something to asin that's much bigger than 1. That'll give you complex results. Is the thing you're passing to asin perhaps meant to be divided by R^2 or DR^2 or something of the kind? You have a similar issue a bit later with the argument to acos.
I also suspect that some of your * and ^ and / operators should actually be elementwise ones .*, .^, ./.
If you're trying to do as you said:
so in first equation i used R= 50, DR
= 0.5, r= 25, k=2 and i need to get h. In second equation i used R=75,
DR=1.0, r=25, k=2...for a last
equation i used
R=600,DR=4.0,r=25,k=2.
DR and R need to be the same length... so if R goes between 50 and 600 in increments of 25, DR should go from 0.5 to 12.5 in increments of 0.5, or 0.5 to 4.0 in increments of 0.1522...
once you figure that out, be sure the add a period before every matrix multiplication operation (e.g. * or ^)
EDIT: formula adjusted slightly (bracketing) to reflect success in comment.
When you say you want a table, I guess it is to be an R by DR table (since you have to vectors of different length). To do that you need to use R as a column vector (R' below) and multiply with * (not .*). When R doesn't appear in a term multiply by ones(size(R)) (or use repmat) to get DR into the right shape. To square DR by element, you need DR.^2. There seems to be a misplaced bracket for the acos, surely you divide by r before taking the acos. There must be a division by something like r in the asin (not r^2 because you've taken the sqrt). Finally, the last division by r is redundant as written, since you multiply by r at the same level just before. Anyway, if I do the following:
h= r*(1-cos(asin((sqrt(2*R'*DR+ones(size(R))'*DR.^2)/r)+sin(acos((r-k)/r)))))-k
I get an R by DR table. Results for small R,DR are real; higher R,DR are complex due to the argument of the first asin being >1. The first entry in the table is 4.56, as you require.