Why is the output giving me a value of +1? - c#

The code
public static void InitializeArray(ref double[] doubleA)
{
//array init using foreach
int i = 0;
foreach (double dub in doubleA)
{
doubleA[i++] = i + .5;
}
}
is giving me an output of
doubleA[0] = 1.5 instead of .5
doubleA[1] = 2.5 instead of 1.5
and so on
I'm not understanding why it's doing that. As I understand it, doubleA[0] should be getting 0.5 because I'm only adding 0.5 so where is the extra 1 coming from? I'm thinking it's from int i but for i=0, shouldn't it evaluate to doubleA[0] = 0 + .5?
So far I have tried writing doubleA[i++] = i + .5; instead which gives each element in the array just the value of 0.5.

So let's start with i = 0
doubleA[i++] = i + .5;
Here you are accessing position 0 of the array, but also adding 1 to the value of i. When i == 0, the expression i++ will be the value 0, but the value of the variable i is incremented such that the new value of i is 1.
On the right hand side, this new value of i is used (1) and added to 0.5. Giving a value of 1.5 which is assigned back to index 0 of the array (as indicated on the left hand side of the assignment).
I could go on, but I think you probably get it by now...
Further reading on operator ++

This is because i is being incremented in your key: doubleA[i++]. i++ will increment the key by one, AFTER returning it. When it's used later (as the value), its value has already been incremented. So now you're setting it to 1 + 0.5.
Let's break this down, and show you the functional equivalent, and you'll see exactly what this is happening:
public static void InitializeArray(ref double[] doubleA)
{
//array init using foreach
int i = 0;
foreach (double dub in doubleA)
{
int key = i;
i = i + 1;
doubleA[key] = i + .5;
}
}

Related

How to Get the value on a specific step closest to my number

I have an arbitrary numeric value (float), and an arbitrary step (also a float).
I want to find the number on the step that would be the closest to the numeric value, without going the long way (stepping until I reach it)
Example:
The step is 5
The value is 1038
The step would go 0 - 5 - 10 - 15 - ... - 1035 - 1040 - ...
The closest value is therefore 1040. This is very easy to find with a loop just searching for the last value before my number, the first value after, and choose the closer one.
But this is O(n), and I want something faster (sometimes the step is very small and the value very big, and this has to be done extremely fast for UI reactions).
Is there a way to do this with just a calculation, without a loop?
EDIT: There is no need to start at 0. The step can be negative or positive (but a step of -40 would give the exact same result as a step of 40). If it is done through a clever calculation instead of a loop, no start point is required.
English is not my native language. I am well aware that "step" is probably the wrong word, but I can'tt find the right one to explain. I hope my example makes my question clearer.
Edits are welcome if anyone knows how to explain it more clearly (including changing the title)
You can just use math to figure it out. First, get the absolute values of value and step, then determine the numbers on either side of step by subtracting value % step from value for the low number, and adding step to the low number for the higher one.
Then just determine which number is closer to value and return that (but first multiply it by the sign of value):
static float GetClosestNumber(float value, float step)
{
// Get the absolute values of our arguments
var absValue = Math.Abs(value);
step = Math.Abs(step);
// Determing the numbers on either side of value
var low = absValue - absValue % step;
var high = low + step;
// Return the closest one, multiplied by -1 if value < 0
var result = absValue - low < high - absValue ? low : high;
return result * Math.Sign(value);
}
Here's a little test method and associated class:
class Item
{
public float Value { get; set; }
public float Step { get; set; }
}
static void Main()
{
var testItems = new List<Item>
{
new Item {Value = 1038, Step = 5},
new Item {Value = .8f, Step = .25f},
new Item {Value = .9f, Step = .25f},
new Item {Value = -86, Step = -45},
new Item {Value = -168, Step = -45},
new Item {Value = -168, Step = 45},
};
foreach (var testItem in testItems)
{
Console.WriteLine("The closest number to {0}\twhen stepping by {1}\tis {2}",
testItem.Value, testItem.Step, GetClosestNumber(testItem.Value, testItem.Step));
}
GetKeyFromUser("\nDone! Press any key to exit...");
}
Output
What about:
int step = 3;
int value = 10;
if ((value % step) == 0)
{
return value;
}
else
{
return ((value / step) + 1) * step;
}

What wrong with this implement of this arcsine approximate in C#

This is a formula to approximate arcsine(x) using Taylor series from this blog
This is my implementation in C#, I don't know where is the wrong place, the code give wrong result when running:
When i = 0, the division will be 1/x. So I assign temp = 1/x at startup. For each iteration, I change "temp" after "i".
I use a continual loop until the two next value is very "near" together. When the delta of two next number is very small, I will return the value.
My test case:
Input is x =1, so excected arcsin(X) will be arcsin (1) = PI/2 = 1.57079633 rad.
class Arc{
static double abs(double x)
{
return x >= 0 ? x : -x;
}
static double pow(double mu, long n)
{
double kq = mu;
for(long i = 2; i<= n; i++)
{
kq *= mu;
}
return kq;
}
static long fact(long n)
{
long gt = 1;
for (long i = 2; i <= n; i++) {
gt *= i;
}
return gt;
}
#region arcsin
static double arcsinX(double x) {
int i = 0;
double temp = 0;
while (true)
{
//i++;
var iFactSquare = fact(i) * fact(i);
var tempNew = (double)fact(2 * i) / (pow(4, i) * iFactSquare * (2*i+1)) * pow(x, 2 * i + 1) ;
if (abs(tempNew - temp) < 0.00000001)
{
return tempNew;
}
temp = tempNew;
i++;
}
}
public static void Main(){
Console.WriteLine(arcsin());
Console.ReadLine();
}
}
In many series evaluations, it is often convenient to use the quotient between terms to update the term. The quotient here is
(2n)!*x^(2n+1) 4^(n-1)*((n-1)!)^2*(2n-1)
a[n]/a[n-1] = ------------------- * --------------------- -------
(4^n*(n!)^2*(2n+1)) (2n-2)!*x^(2n-1)
=(2n(2n-1)²x²)/(4n²(2n+1))
= ((2n-1)²x²)/(2n(2n+1))
Thus a loop to compute the series value is
sum = 1;
term = 1;
n=1;
while(1 != 1+term) {
term *= (n-0.5)*(n-0.5)*x*x/(n*(n+0.5));
sum += term;
n += 1;
}
return x*sum;
The convergence is only guaranteed for abs(x)<1, for the evaluation at x=1 you have to employ angle halving, which in general is a good idea to speed up convergence.
You are saving two different temp values (temp and tempNew) to check whether or not continuing computation is irrelevant. This is good, except that you are not saving the sum of these two values.
This is a summation. You need to add every new calculated value to the total. You are only keeping track of the most recently calculated value. You can only ever return the last calculated value of the series. So you will always get an extremely small number as your result. Turn this into a summation and the problem should go away.
NOTE: I've made this a community wiki answer because I was hardly the first person to think of this (just the first to put it down in a comment). If you feel that more needs to be added to make the answer complete, just edit it in!
The general suspicion is that this is down to Integer Overflow, namely one of your values (probably the return of fact() or iFactSquare()) is getting too big for the type you have chosen. It's going to negative because you are using signed types — when it gets to too large a positive number, it loops back into the negative.
Try tracking how large n gets during your calculation, and figure out how big a number it would give you if you ran that number through your fact, pow and iFactSquare functions. If it's bigger than the Maximum long value in 64-bit like we think (assuming you're using 64-bit, it'll be a lot smaller for 32-bit), then try using a double instead.

How to display all members of a given subsequence on the console?

I'm trying to understand why I can't print only the members of a subsequence of an array, that is equal to an integer from the input. The array is also read from the console. When i run the program only the first of these members does come up, but with him also a seemingly random number of zeros, while the rest of the subsequence is omitted. If there's a better way than to use a second array, I'll be grateful if you share it. Okay, to specify- I want to know how to print all the members of the aforementioned subsequence, can you please give me a useful advice or sample? Here's the input, output and code:
4 4 56 57 58
8
4 0 0 0 0
instead of 4 4
int v = int.Parse(Console.ReadLine());
int[] valueHolder = new int[arr1.Length];
int currentSum = 0;
for (int endIndex = 0; endIndex <= arr1.Length -1; endIndex++)
{
currentSum = 0;
for (int currentSumIndex = endIndex; currentSumIndex >= 0; currentSumIndex--)
{
currentSum += arr1[currentSumIndex];
if (currentSum == v)
{
valueHolder[currentSumIndex] = arr1[currentSumIndex];
}
if (currentSum == v)
{
for (int i = 0; i <= valueHolder.Length - 1; i++)
{
Console.Write(valueHolder[i] + " ");
}
}
}
I think you would be best served by putting a break point on the line of the first for loop then stepping through your code. If you take a pad of paper and write each of the variables states as you go through it then it will be pretty obvious what's going on.
However, just to help you out.
In the first pass of the outer loop (endIndex = 0), the inner loop does NOT execute. currentSumIndex = endIndex which equals zero, which does not pass the currentSumIndex >= 0 test. Therefore the first 4 is skipped.
In the second pass, the number 4 is emitted because currentSum equals 4. However, the values of 0 are also emitted because you are walking the entire valueHolder array and spitting all of the empty values out.
From the third pass forward, currentSum will never equal the number you typed in:
The first pass of the inner loop sets currentSum to 56, which does not equal v. The second pass of the inner loops sets it to 56+4 ( currentSum += arr1[currentSumIndex] ) which is 60. Therefore, nothing will ever be emitted again as currentSum will always be the sum of all numbers from the current array position going backward to the beginning array position and therefore will always be greater than v
You don't need a second array. You just need to pay attention to what your code is doing. Side note: I have absolutely no idea why you have that inner loop or even what the 8 is supposed to represent in your example entry above.
If I was writing this, I'd change it to (assuming you can't use LINQ):
int v = int.Parse(Console.ReadLine());
for (int i= 0; i <= arr1.Length -1; i++)
{
if (arr1[i] == v) {
Console.Write(arr1[i].ToString() + " ");
}
}
Console.WriteLine();

Increase an int by one

On another page I've said that nr = 0
var number = this.NavigationContext.QueryString["nr"];
int Nr = Convert.ToInt16(number);
And this works, Nr = 0
Now I want to upgrade Nr by one:
int next = Nr++;
Unfortunately this doesn't work... next = 0 too, but it supposed to be 1.
Could someone explain to me what I'm doing wrong?
Nr++ increments and returns the original value of Nr.
++Nr increments and returns the new value of Nr. So what you want is:
int next = ++Nr;
In C# (or C++), the statement
int next = Nr++;
translates to, "assign the value of Nr to variable next, and then increment Nr by 1.
If you want Nr to increment first, your statement should look like this:
int next = ++Nr;
Here is the definition of the ++ operator: http://msdn.microsoft.com/en-us/library/36x43w8w.aspx
the problem is ...Nr is incremented after Nr set to next use next=Nr+1;
There are two increment operators - pre-increment ++c and post-increment c++.
var x = ++c; is equivalent to
c = c + 1;
var x = c;
while var x = c++; is equivalent to
var x = c;
c = c + 1;
and therefore x either receives the value before or after c got incremented.

Order of operations when working with array index

Consider this loop:
int[] myArray = new int[10];
int myIndex = 0;
for (int i = 0; i < 10; i++)
{
myArray[myIndex++] = myIndex;
Console.WriteLine(myArray[i]);
}
This yields:
1
2
3
...
Because myIndex is post-incremented, and the right side is evaluated first, shouldn't the array index 0 contain 0?
Can someone explain this order-of-operations misunderstanding for me?
The right side isn't necessarily evaluated first. Similar to:
foo.Bar.Baz = a + b;
In the above code, foo.Bar is evaluated first, then a + b, then the set_Baz method is called to set the Baz property to whatever is evaluated on the right.
So in your code, if you break it into pieces, it looks like this:
var index = i;
// post-incremented in the original code means this comes after the line above,
// but not after the line below it.
i += 1;
myArray[index] = i;
first run:
myArray[myIndex++] = myIndex;
* *
| |
zero one
myIndex++ gets executed after myArray[myIndex++], but any subsequent calls with have the already incremented variable.
The myIndex++ is executing before the value is being set because the array index takes precident so it knows what array index to set the value to.
The...
myArray[myIndex++] = myIndex;
...is equivalend to...
int tmp = myIndex;
++myIndex;
myArray[tmp] = myIndex;
The myIndex++ is evaluated first, followed by the left side and finally the assign operator, according to precedence

Categories

Resources