Here is my problem: I have a if statement regrouping multiple conditions eg: if(stat1 & stat2 & stat3 & stat4).
in this condition, I want to compare 4 times 2 numbers.
If the number 1 is negative and the number 2 positive, I want the if statement to be if(num1 >= num2 & ....). If the number 1 is positive and the number 2 is negative, I want the if statement to be if(num1 <= num2 & ...). If the numbers are both positive but number 1 is smaller, I want it to be if(num1 >= num2 & ...)
And I think you get it.
the problem is that i can't just make multiple if statements for every possibilities, since there are something like 8 cases per conditions and 4 conditions. Is there anyway I can adapt my if statement to fit my needs in the script ?
In my case, my number one would be the x angle of a gameobject, and number 2 the x angle I want to get. My gameobject is being rotated in update with Time.deltaTime, but since it goes realyl fast, I can't just do if(number1 != number2), cause it would just skip it until it lands on it, and since I have 4 times 2 numbers, all the 4 numbers would need to fall on the good value, so I want to use <= or >=, for these reasons. My angles should stay between the interval (number1, number2), thats why I can't allow it to do a full 360 degree rotation, and I need to detect as soon as it passes the value. And I already have some code that choses whether I have to do Time.deltaTime * 1 or Time.deltaTime * -1, and it is important to never get a rotation around 180 degree.
You can use the Abs function in the System.Math class. This function does return the distance between 0 and the number. That way it doesn't matter wich one is positive or negative
if (System.Math.Abs(num1) >= System.Math.Abs(num2))
{
// Its here for n1= -150 and n2 = 120
// Also here for n1 = 150 and n2 = -120
// Also here when n1 and n2 are the same
}
else{
// Its outside for n1 = -100 and n2 = 120
// Also outside for n1 = 100 and n2 = 120
}
I would suggest to use nested if statements and try to reduce the number of combinations if possible.
I'm not sure if you really need to know if the number is negative or not maybe you could utilize math absolute value. Provide more context and put more efforts in the question in order for us to help you better.
Edit:
Then why don't you check the abs value of the first rotation and if it exceeds 180 degrees then do the second rotation?
Related
Exercise Background
The exercise consists in generating a 2D map with a user given x,y size of said map, and then place on each cell of the map random items from a table.
I have a cell in an [x, y] coordinate of an Items matrix and I have to pick items randomly for every cell of this matrix.
My Problem
I have to select random items from a table of 4 items that have their probabilities shown in cumulative probability, and a cell that has such items can have more than 1 and different combinations of those items.
I don't really know how to go about this problem, taking in account that 2 of the items have the same probability on the given table for the homework.
This is the table of probability given:
Food - 1
Weapons - 0.5
Enemy - 0.5
Trap - 0.3
My Items enumeration:
[Flags]
enum Items
{
Food = 1<<0,
Weapon = 1<<1,
Enemy = 1<<2,
Trap = 1<<3
}
Again, the expected output is to pick randomly through this percentages what items does 1 cell have. What I'd like to have as an answer would be just a start or a way to go about this problem please, I still want to try and do it myself, avoid complete code solutions if you can.
I find it easier to work with integers in this type of problem, so I'll work with:
Food - 10
Weapons - 5
Enemy - 5
Trap - 3
That gives a total of 10 + 5 + 5 + 3 = 23 total possible options.
Most computer RNGs work from base 0, so split the 23 options (as in 0..22) like this:
Food - 0..9 giving 10 options.
Weapons - 10..14 giving 5 options.
Enemy - 15..19 giving 5 options.
Trap - 20..22 giving 3 options.
Work through the possibilities in order, stopping when you reach the selected option. I will use pseudocode as my C++ is very rusty:
function pickFWET()
pick <- randomInRange(0 to 22);
if (pick < 10) return FOOD;
if (pick < 15) return WEAPONS;
if (pick < 20) return ENEMY;
if (pick < 23) return TRAP;
// If we reach here then there was an error.
throwError("Wrong pick in pickFWET");
end function pickFWET
If two items have the same cumulative probability then the probability of getting the latter item is 0. Double check the probability table, but if it is correct, then 'Weapons' is not a valid option to get.
However in general. If you could 'somehow' generate a random number between 0 and 1, the problem would be easy right? With a few if conditions you can choose one of the options given this random number.
With a little bit of search you can easily find how to generate a random number in whatever language you desire.
I feel really stupid about this but i'm having some problems with calculating the change in % when working with negative numbers.
The calculation i'm using gives a satisfying result when the numbers are > 0.
decimal rateOfChange = (newNumber - oldNumber) / Math.Abs(oldNumber);
Lets say i have two numbers 0.476(newNumber) and -0.016(oldNumber) that's an increase of 0.492 and with my calculation the rate of change is 3 075%.
If i instead have 0.476(newNumber) and 0.001(oldNumber) that's an increase of 0.475 and my calculation will give me the rate of change of 47 500% wich seems correct.
Blue line represent example one and red line is example two. In my world blue line should have bigger % change.
How would i write this calculation to give me the correct % change when also dealing with negative numbers? I want it to handle both increases and decreases in the % change.
I understand this is a math issue and i need to work on my math
Seems to work for me.
decimal newNumber = 0.476m;
decimal oldNumber = -0.016m;
decimal increase = newNumber - oldNumber; // this is 0.492 which is true
decimal rateOfChange = increase / Math.Abs(oldNumber);
rateOfChange is equal to approximately 30.75 which is 3075% which is the correct change.
The second example works too. The increase is -0.475 which gives the rateOfChange equal to -475 which is equal to -47500% which is correct.
You are mixing two concepts: absolute and relative deviation.
You seem to expect that bigger absolute deviations imply bigger relative deviations, which is false. You also seem to think that negative numbers is the cause of the unexpected (but correct) results you are getting.
Relative deviation depends on the magnitude of the absolute deviation and the magnitude of your reference value, not its sign. You can have smaller absolute deviations that imply really big relative deviations and vice versa.
old value: 1
new value: 100
abs. deviation: 99
rel. deviation: 99
old value: .00001
new value: 1
abs deviation: .99999
rel deviation: 99999
There are the obvious quirks of Math.Round but is there a way to make Math.Round fulfill this type of manipulation for a rating system.
If greater than .0 and less than or equal to .5, display half a star
If greater than .5 and less than or equal to .0 display whole star
So obviously a half star would be .5 and a whole start would be the next whole value.
I don't know of a rounding method to go to half whole numbers.
Should I just write if statements to control my rounding?
**Edit/Solution
From the below answer I came up with.
double roundedRating = (Math.Ceiling(2 * currentRating)) / 2;
I'd recommend multiplying by two, performing Math.Ceiling, and dividing by two to get to the nearest half.
You're going to want to make sure that you end up performing your checks against integers, rather than floating point numbers.
Start by multiplying the number by 2. Continue doing this until it's an integer value (no value in the decimal part).
Now, continuously divide by 2 until you end up with a number that's less than or equal to the original number. If the result decimal part is greater than .0 and less than or equal to .5, display half a star. If it's greater than .5 and less than or equal to +.0, display a whole star.
Actually, go with matt's answer. ; )
Can this work?
Multiply the number by 10 e.g. 0.1x10, 0.2x10 to get n
Math.Ceil(n / 5) / 2
where n = 1, 2, 3 instead of - .1, .2, .3
examples:
1,2,3,4,5 = 1/2 = 0.5
6,7,8,9,10 = 2/2 = 1
11,12,13,14,15 = 3/2 = 1.5
If efficiency is no issue, the following approach could be used:
Number *= 10;
Number % 10 = remainder;
if(remainder <=5 && remainder != 0)
//Half star
else
//Whole star
However, that code is kinda ugly, but I think it gives you the general idea.
double roundedRating = (int)(currentRating * 2D + 0.999999999999999) / 2D
I'm trying to create something that sort of resembles a histogram. I'm trying to create buckets from an array.
Suppose I have a random array doubles between -10 and 10; this is very simplified. I then want to specify a center point, in this case 0 and the number of buckets.
If I want 4 buckets the division would be -10 to -5, -5 to 0, 0 to 5 and 5 to 10. Not that complicated right. Now if I change the min and max to -12 and -9 and as for 4 divisions its more complicated. I either want a division at -3 and 3; it is centered around 0 ; or one at -6 to 0 and 0 to 6.
Its not that hard to find the division size
= Math.Ceiling((Abs(Max) + Abs(Min)) / Divisions)
Then you would basically have an if statement to determine whether you want it centered on 0 or on an edge. You then iterate out from either 0 or DivisionSize/2 depending on the situation. You may not ALWAYS end up with the specified number of divisions but it will be close. Then you iterate through the array and increment the bin count.
Does this seem like a good way to go about this? This method would surely work but it does not seem to be the most elegant. I'm curious as to whether the creation of the bins and the counting from the list could be done in a clever class with linq in a more elegant way?
Something like creating the bins and then having each bin be a property {get;} that returns list.Count(x=> x >= Lower && x < Upper).
To me it seems simpler: You need to find lower bound and size of each "division".
Since you want it to be symmetrical around 0 depending on number of divisions you either get one that includes 0 for odd numbers (-3,3) or around 0 for even ones (-3,0)(0,3)
lowerBound = - Max(Abs(from), Abs(to))
bucketSize = 2 * lowerBound / divisions
(throw in Ceiling and update bucketSize and lowerBound if needed)
Than use .Aggregate to update array of buckets (position would be (value-lowerBound)/devisions, with additional range checks if needed).
Note: do not implement get the way you suggested - it is not expected for getters to perfomr non-trivial work like walking large array.
If tan(x) = y and atan(y) = x why Math.Atan(Math.Tan(x)) != x?
I´m trying to calculate x in something like:
tan(2/x +3) = 5
so
atan(tan(2/x + 3) = atan(5)
and so on... but I´ve tried this:
double d = Math.Atan(Math.Tan(10));
and d != 10. Why?
The tangent function is periodic with period pi, and is invertible only if you restrict it to a subset of its domain over which it is injective. Usually the choice of such set is the open interval ]-pi/2, pi/2[, hence the arctan function will always return a point in that interval. In your case, 10 = 3*pi + 0.57522... Thus, the arctan of the tangent of 10 will return 0.57522...
Note that the arctan function, defined as above, is injective and defined over all the real numbers, hence the converse of your problem math.tan(math.atan(x)) == x
indeed holds for each x (except for numerical errors).
In order to deal with numerical errors, you should never perform comparisons between the results of floating point computations using == or !=. Use abs(number1 - number2) < epsilon // ==
abs(number1 - number2) >= epsilon // !=
instead, where epsilon is a small positive constant.
A graph might help explain why you are not getting the result you expected.
(source: wolfram.com)
http://mathworld.wolfram.com/Tangent.html
That shows the graph of Tan, but if you imagine reading off a value of x for a given y, (e.g. y = 0) then depending on which "strand" of Tan you read, you will get a different answer (-pi, 0, pi...). That's the point about Arctan(x) having more than one solution.
If arctan was restricted to only one of those strands, e.g. -pi/2 < x < pi/2 then Arctan(tan(x)) will return x providing you have accounted for floating point errors.
EDIT: However, according to http://msdn.microsoft.com/en-us/library/system.math.atan.aspx, the atan method already returns -pi/2 < x < pi/2 or NaN if your input is undefined. So the problem must soley be down to floating point rounding.
EDIT (F.R.): Added figure
I dont know any C#, but maths says that tan is not invertable, only in a small intervall.
e.g. tan(pi) = 0 and tan(0) = 0. When asking for atan(0) it could be 0 or pi (or every multiple of pi), so the result is in the range from -pi/2 .. pi/2.
Even if you start with an x in the invertable range i doesnt has to work, because of rounding errors with the floating points (it has not unlimmited precision).
tan-1(tan(x)) == x for all x in (-PI/2, PI/2).
Because the tangent function is periodic we need to normalize input angle. Math.Atan returns an angle, θ, measured in radians, such that -π/2 ≤ θ ≤ π/2, so it makes sense to normalize to that range (since it obviously won't anything within that range anyway):
double normalizedAngle = (angle + Math.PI / 2) % Math.PI - Math.PI / 2;
Doubles should be compared with some error margin. But in fact for this case Double.Epsilon is too small and "If you create a custom algorithm that determines whether two floating-point numbers can be considered equal, you must use a value that is greater than the Epsilon constant to establish the acceptable absolute margin of difference for the two values to be considered equal. (Typically, that margin of difference is many times greater than Epsilon.)" For instance, Math.Atan(Math.Tan(-0.49999632679501449)) + 0.49999632679501449 will be greater than Double.Epsilon for 1.1235582092889474E+307 times.
It might be helpful if you posted what you are trying to accomplish. I have recollections of discovering trig functions that handled the issue if what quadrant the inputs were in for me when I tried playing with angles, for example.
In general, when you are dealing with floating point numbers, you are dealing with approximations. There are numbers that cannot be represented exactly, and the tan and arctan operations are themselves only approximate.
If you want to compare floating point numbers, you need to ask if they are nearly equal, or equivalently, if the difference is less than some small value, and think carefully what you are doing.
Here is are some FAQS (for c++, but the idea is the same), that talk a bit about some of the oddities of floating point numbers:
FAQ 29.16
FAQ 29.17
FAQ 29.18
Edit: Looking at the other answers, I realise that the main problem is probably that tan isn't invertible, but the approximation issue is worth considering too, whenever you test floating point numbers for equality.
Looking at the .net documentation for Math.Atan, atan produces a value between -π/2 and ≤ π/2, which doesn't include 10. That I think is the usual range for arctan.
double d = Math.Atan(1) * (180 / Math.PI);
so d will be 45 in degrees