I wanted to figure out a way to make my floating points move and change faster than the typical x++ so I decided to add more of those increments into the same while loop so they stack
While (True)
{
x++;
x++;
x++;
x++;
}
The functionality works but how do i do this with shorter code?
You can replace that with:
while (...)
{
x += 4;
}
This represents x = x + 4
You can also do this with subtraction, multiplication, and division, respectively -=, *=, and /=. Read more here
x += 4; // Adds 4 to x, and stores the result in x.
Try += operator:
x+=4;
in this way x will be incremented by 4.
Related
What is the difference between these unary operators in C#?
What would an example be? What is the name of each?
+= vs. =+
++x vs. x++
They differ in how they change the value and how they return the result.
The first two += and =+ behave in the way that the first increments a variable, the other sets a variable. They are not related. Observe the following code:
// +=
x = 1;
printf( x += 1 ); // outputs 2, the same as x = x+1
printf( x ); // outputs 2
// =+
x = 1;
printf( x =+ 1 ); // outputs 1, the same as x = 1;
printf( x ); // outputs 1
The next two, ++x and x++, differ in the order their function. ++x will increment your variable by 1 and return the result. x++ will return the result and increment by 1.
// ++x
x = 1;
printf( ++x ); // outputs 2, the same as x = x+1
printf( x ); // outputs 2
// x++
x = 1;
printf( x++ ); // outputs 1
printf( x ); // outputs 2
They are mostly useful for for loops and while loops.
In terms of speed, ++x is considered a lot faster than x++ since x++ needs to create an internal temporary variable to store the value, increment the main variable, but return the temporary variable, basically more operations are used. I learned this a looong time ago, I don't know if it still applies
Let's visualize the first ones, += and =+.
Because "+" is action, "=" is assignment, so
+= is to add BEFORE assignment
=+ is a bit confusing with "+", it could be "-", for example a=+7 or a=-7, anyway, it's a direct assignment.
Similarly,
++x is "increment then return"
x++ is "return then increase"
++x vs x++ are unary operators. ++x means pre increment and x++ means post increment.
int temp;
temp = 1;
Console.WriteLine(++temp); // Outputs 2
temp = 1;
Console.WriteLine(temp++); // outputs 1
Console.WriteLine(temp); // outputs 2
Prefix increment means:
The result of the operation is the value of the operand after it has
been incremented.
Postfix increment means:
The result of the operation is the value of the operand before it has
been incremented.
Now the following:
+= means temp += 10; // same as temp = temp + 10;
This =+ isn't a valid operator.
If one does this:
str = + str; // will throw an error.
int a;
a = +2; // sort of meaningless . 2 and +2 means same.
More here: Is there such thing as a "=+" operator?
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/increment-operator
I have a simple algebraic relationship that uses three variables. I can guarantee that I know two of the three and need to solve for the third, but I don't necessarily know which two of the variables I will know. I'm looking for a single method or algorithm that can handle any of the cases without a huge batch of conditionals. This may not be possible, but I would like to implement it in a more general sense rather than code in every relationship in terms of the other variables.
For example, if this were the relationship:
3x - 5y + z = 5
I don't want to code this:
function(int x, int y)
{
return 5 - 3x + 5y;
}
function(int x, int z)
{
return (5 - z - 3x)/(-5);
}
And so on. Is there a standard sort of way to handle programming problems like this? Maybe using matrices, parameterization, etc?
If you restrict yourself to the kind of linear functions shown above, you could generalize the function like this
3x - 5y + z = 5
would become
a[0]*x[0] + a[1]*x[1] + a[2]*x[2] = c
with a = { 3, -5, 1 } and c = 5.
I.e., you need a list (or array) of constant factors List<double> a; and a list of variables List<double?> x; plus the constant on the right side double c;
public double Solve(IList<double> a, IList<double?> x, double c)
{
int unknowns = 0;
int unkonwnIndex = 0; // Initialization required because the compiler is not smart
// enough to infer that unknownIndex will be initialized when
// our code reaches the return statement.
double sum = 0.0;
if (a.Count != x.Count) {
throw new ArgumentException("a[] and x[] must have same length");
}
for (int i = 0; i < a.Count; i++) {
if (x[i].HasValue) {
sum += a[i] * x[i].Value;
} else {
unknowns++;
unknownIndex = i;
}
}
if (unknowns != 1) {
throw new ArgumentException("Exactly one unknown expected");
}
return (c - sum) / a[unknownIndex];
}
Example:
3x - 5y + z = 5
5 - (- 5y + z)
x = --------------
3
As seen in the example the solution consists of subtracting the sum of all terms except the unknown term from the constant and then to divide by the factor of the unknown. Therefore my solution memorizes the index of the unknown.
You can generalize with powers like this, assuming that you have the equation
a[0]*x[0]^p[0] + a[1]*x[1]^p[1] + a[2]*x[2]^p[2] = c
you need an additional parameter IList<int> p and the result becomes
return Math.Pow((c - sum) / a[unknownIndex], 1.0 / p[unknownIndex]);
as x ^ (1/n) is equal to nth-root(x).
If you use doubles for the powers, you will even be able to represent functions like
5
7*x^3 + --- + 4*sqrt(z) = 11
y^2
a = { 7, 5, 4 }, p = { 3, -2, 0.5 }, c = 11
because
1
x^(-n) = ---
x^n
and
nth-root(x) = x^(1/n)
However, you will not be able to find the roots of true non-linear polynomials like x^2 - 5x = 7. The algorithm shown above, works only, if the unknown appears exactly once in the equation.
Yes, here is one function:
private double? ValueSolved (int? x, int? y, int? z)
{
if (y.HasValue && z.HasValue && !x.HasValue
return (5 + (5 * y.Value) - z.Value) / 3;
if (x.HasValue && z.HasValue && !y.HasValue
return (5 - z.Value - (3 * x.Value)) / -5;
if (x.HasValue && y.HasValue && !z.HasValue
return 5 - (3 * x.Value) + (5 * y.Value);
return null;
}
There is no standard way of solving such a problem.
In the general case, symbolic math is a problem solved by purpose built libraries, Math.NET has a symbolic library you might be interested in: http://symbolics.mathdotnet.com/
Ironically, a much tougher problem, a system of linear equations, can be easily solved by a computer by calculating an inverse matrix. You can set up the provided equation in this manner, but there are no built-in general purpose Matrix classes in .NET.
In your specific case, you could use something like this:
public int SolveForVar(int? x, int? y, int? z)
{
int unknownCount = 0;
int currentSum = 0;
if (x.HasValue)
currentSum += 3 * x.Value;
else
unknownCount++;
if (y.HasValue)
currentSum += -5 * y.Value;
else
unknownCount++;
if (z.HasValue)
currentSum += z.Value;
else
unknownCount++;
if (unknownCount > 1)
throw new ArgumentException("Too Many Unknowns");
return 5 - currentSum;
}
int correctY = SolveForVar(10, null, 3);
Obviously that approach gets unwieldy for large variable counts, and doesn't work if you need lots of dynamic numbers or complex operations, but it could be generalized to a certain extent.
I'm not sure what you are looking for, since the question is tagged symbolic-math but the sample code you have is producing numerical solutions, not symbolic ones.
If you want to find a numerical solution for a more general case, then define a function
f(x, y, z) = 3x - 5y + z - 5
and feed it to a general root-finding algorithm to find the value of the unknown parameter(s) that will produce a root. Most root-finding implementations allow you to lock particular function parameters to fixed values before searching for a root along the unlocked dimensions of the problem.
I need to find a division of two integers and round it to next upper integer
e.g x=7/y=5 = 2; here x and y always greater than 0
This is my current code
int roundValue = x % y > 0? x / y + 1: x / y;
Is there any better way to do this?
You could use Math.Ceiling... but that will require converting to/from double values.
Another alternative is to use Math.DivRem to do both parts at the same time.
public static int DivideRoundingUp(int x, int y)
{
// TODO: Define behaviour for negative numbers
int remainder;
int quotient = Math.DivRem(x, y, out remainder);
return remainder == 0 ? quotient : quotient + 1;
}
Try (int)Math.Ceiling(((double)x) / y)
All solutions looks too hard. For upper value of x/y, use this one
( x + y - 1 ) / y
dunno what's better way or how to define a better way (if in terms of performance you have to run tests to see which will be faster), but here's my solution:
int roundValue = x / y + Convert.ToInt32(x%y>0);
p.s.
still have to deal somehow with neg. numbers... IMO this is the simplest.
+0.5 will aways round to the higher.
Use ceil() function.
It gives the upper value.
It's better to use MidpointRounding from Math.Round
In your case:
Math.Round(value, MidpointRounding.AwayFromZero);
see more: https://learn.microsoft.com/ru-ru/dotnet/api/system.math.round?view=net-6.0#system-math-round(system-double-system-midpointrounding)
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
C#: what is the difference between i++ and ++i?
I see this operator (++) very often. I know what it does ultimately, but it seems like there's some rules I don't understand. For example, it seems to matter if you put it before or after the variable you're using it on. Can someone explain this?
The statement
x++;
is exactly equivalent to
x = x + 1;
except that x is evaluated only once (which makes a difference if it is an expression involving property getters).
The difference between the following two:
DoSomething(x++); // notice x first, then ++
DoSomething(++x); // notice ++ first, then x
Is that in the first one, the method DoSomething will see the previous value of x before it was incremented. In the second one, it will see the new (incremented) value.
For more information, see C# Operators on MSDN.
It is possible to declare a custom ++ operator for your own classes, in which case the operator can do something different. If you want to define your own ++ operator, see Operator Overloading Tutorial on MSDN.
http://msdn.microsoft.com/en-us/library/36x43w8w(v=VS.80).aspx
The increment operator (++) increments its operand by 1. The increment operator can appear before or after its operand:
The first form is a prefix increment operation. The result of the operation is the value of the operand after it has been incremented.
The second form is a postfix increment operation. The result of the operation is the value of the operand before it has been incremented.
If you put the ++ operator before the variable, it is incremented first.
If you put the ++ operator after the variable, it is incremented after.
For example(C#):
int x = 0;
Console.WriteLine("x is {0}", x++); // Prints x is 0
int y = 0;
Console.WriteLine("y is {0}", ++y); // Prints y is 1
Hope this cleared it up.
well if you put it like
variable++
It first uses the variable and the increments it (+1)
On the otherhand if you
++variable
It first increments the variable and then uses it
Another way to see it... here are two functions that do the same as prefix/postfix ++. This illustrates that prefix is, in theory, faster, because no temporary variable is needed to store the "previous" value:
// same as x ++;
int PostfixIncrement(ref int x)
{
int y = x;
x = x + 1;
return y;
}
// same as ++ x;
int PrefixIncrement(ref int x)
{
x = x + 1;
return x;
}
If you put the ++ operator before the variable, it is incremented first. If you put the ++ operator after the variable, it is incremented after.
For example(C#):
int x = 0;
Console.WriteLine("x is {0}", x++); // Prints x is 0
int y = 0;
Console.WriteLine("y is {0}", ++y); // Prints y is 1
I understand that floating point arithmetic as performed in modern computer systems is not always consistent with real arithmetic. I am trying to contrive a small C# program to demonstrate this. eg:
static void Main(string[] args)
{
double x = 0, y = 0;
x += 20013.8;
x += 20012.7;
y += 10016.4;
y += 30010.1;
Console.WriteLine("Result: "+ x + " " + y + " " + (x==y));
Console.Write("Press any key to continue . . . "); Console.ReadKey(true);
}
However, in this case, x and y are equal in the end.
Is it possible for me to demonstrate the inconsistency of floating point arithmetic using a program of similar complexity, and without using any really crazy numbers? I would like, if possible, to avoid mathematically correct values that go more than a few places beyond the decimal point.
double x = (0.1 * 3) / 3;
Console.WriteLine("x: {0}", x); // prints "x: 0.1"
Console.WriteLine("x == 0.1: {0}", x == 0.1); // prints "x == 0.1: False"
Remark: based on this don't make the assumption that floating point arithmetic is unreliable in .NET.
Here's an example based on a prior question that demonstrates float arithmetic not working out exactly as you would think.
float f = (13.45f * 20);
int x = (int)f;
int y = (int)(13.45f * 20);
Console.WriteLine(x == y);
In this case, false is printed to the screen. Why? Because of where the math is performed versus where the cast to int is happening. For x, the math is performed in one statement and stored to f, then it is being cast to an integer. For y, the value of the calculation is never stored before the cast. (In x, some precision is lost between the calculation and the cast, not the case for y.)
For an explanation behind what's specifically happening in float math, see this question/answer. Why differs floating-point precision in C# when separated by parantheses and when separated by statements?
My favourite demonstration boils down to
double d = 0.1;
d += 0.2;
d -= 0.3;
Console.WriteLine(d);
The output is not 0.
Try making it so the decimal is not .5.
Take a look at this article here
http://floating-point-gui.de/
try sum VERY big and VERY small number. small one will be consumed and result will be same as large number.
Try performing repeated operations on an irrational number (such as a square root) or very long length repeating fraction. You'll quickly see errors accumulate. For instance, compute 1000000*Sqrt(2) vs. Sqrt(2)+Sqrt(2)+...+Sqrt(2).
The simplest I can think of right now is this:
class Test
{
private static void Main()
{
double x = 0.0;
for (int i = 0; i < 10; ++i)
x += 0.1;
Console.WriteLine("x = {0}, expected x = {1}, x == 1.0 is {2}", x, 1.0, x == 1.0);
Console.WriteLine("Allowing for a small error: x == 1.0 is {0}", Math.Abs(x - 1.0) < 0.001);
}
}
I suggest that, if you're truly interested, you take a look any one of a number of pages that discuss floating point numbers, some in gory detail. You will soon realize that, in a computer, they're a compromise, trading off accuracy for range. If you are going to be writing programs that use them, you do need to understand their limitations and problems that can arise if you don't take care. It will be worth your time.
double is accurate to ~15 digits. You need more precision to really start hitting problems with only a few floating point operations.