Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I am trying to utilize the Math.Cos() function in c# to print a range of of values from 0 to 2pi increasing by .1pi, so 20 iterations. The problem is I cannot get my x value to change as the for loop is executing.
public void Cos()
{
double x = 0;
double a = Math.PI * x;
double b = Math.Cos(a);
for (int i = 0; i < 21; i++)
{
Console.WriteLine("Cos({0})pi = {1}", x, b);
x += .1;
}
}
When I print the results to the console, it only remembers the value of cos at x = 0. So I just get 1, 20 times as a result for Cos(.1)pi, Cos(.2)pi, etc...
I am trying to utilize the Math.Cos() function in c# to print a range of of values from 0 to 2PI increasing by .1PI
This sounds like a job for a for loop, where we start with a value of 0, and increment by .1 * PI on each iteration until it reaches 2 * PI.
Since a for loop has an initializer part, a condition part, and an incrementing part, it is the perfect construct. No need for an extra variable that increments from 0 to 20 - we can use the for loop to do our incrementing of x and our testing the exit condition!
public static void Cos()
{
for (double x = 0; x <= Math.PI * 2; x += Math.PI * .1)
{
Console.WriteLine("Cos({0})PI = {1}", x, Math.Cos(x));
}
}
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 months ago.
This post was edited and submitted for review 6 months ago and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
I need a method to return the firsts non zero numbers from a double in the following way: Any number >= 1 or == 0 will return the same; All the rest will return as per the following examples:
(Please note that I am using double because the potential imprecision is irrelevant in the use case whereas saving memory is relevant).
double NumberA = 123.2; // Returns 123.2
double NumberB = 1.2; // Returns 1.2
double NumberC = 0.000034; // Returns 3.4
double NumberD = 0.3; // Returns 3.0
double NumberE = -0.00000087; // Returns -8.7
One option would be to iteratively multiply by 10 until you get a number greater than 1:
public double RemoveLeadingZeros(double num)
{
if (num == 0) return 0;
while(Math.Abs(num) < 1) { num *= 10};
return num;
}
a more direct, but less intuitive, way using logarithms:
public double RemoveLeadingZeros(double num)
{
if (num == 0) return 0;
if (Math.Abs(num) < 1) {
double pow = Math.Floor(Math.Log10(num));
double scale = Math.Pow(10, -pow);
num = num * scale;
}
return num;
}
it's the same idea, but multiplying by a power of 10 rather then multiplying several times.
Note that double arithmetic is not always precise; you may end up with something like 3.40000000001 or 3.3999999999. If you want consistent decimal representation then you can use decimal instead, or string manipulation.
I would start with converting to a string. Something like this:
string doubleString = NumberC.ToString();
I don't know exactly what this will output, you will have to check. But if for example it is "0.000034" you can easily manipulate the string to meet your needs.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I'm trying to set my code for counting math games, all math operations are fine except for division. I don't know how to set the while loop correctly. There is a problem with division, such that I would like the division to be residual, so I came up with one method which is given below. It is all in WPF Application. I would like to count only single-digit numbers.
Random number = new Random();
int maxValue = 10;
int total = 0;
int firstNumber = number.Next(1, maxValue);
int secondNumber = number.Next(1, firstNumber);
while (firstNumber % secondNumber != 0);
{
secondNumber++;
}
total = firstNumber / secondNumber;
Why does it still show me the values that have a residual division?
Thank you for any advice
The semi colon at the end of line:
while (firstNumber % secondNumber != 0);
...ends the while loop. The code in the remaining block is executed without any condition (as it in fact is a anonymous block):
{
secondNumber++;
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I am trying to round a number and the expected output isn't correct. Here's what I have tried:
var percent = Math.Round(1.13451, 0);
That above return's 1, but I want it to return 1.13 if the 3rd number is less than 5. If it's >= 5 (the third number) I want to get something like 1.135. I am sure it's something simple I am missing, but not sure.
It appears you are causing confusion because you're using the term "rounding" to describe an operation that is not actually rounding.
I've read your description again, and I can see that you're trying to truncate your values into the highest discrete increment of 0.005 that does not exceed the value.
You can do this as follows:
var percent = Math.Floor(200.0 * x) / 200.0;
Or, if you want it to be more obvious what's happening, this is essentially the same thing:
var increment = 0.005
var percent = Math.Floor(x / increment) * increment;
you have to write it with the amount of decimals you want. var percent = Math.Round(1.13451, 2);
Updated: I think this is the easiest way to do it.
static void Main(string[] args)
{
var percent = 1.13551;
char[] percent1 = percent.ToString().ToCharArray();
if (percent1[4] <= 5)
{
percent = Math.Round(percent, 3);
}
else
{
percent = Math.Round(percent, 2);
}
Console.WriteLine(percent);
Console.Read();
}
Use:
var percent = Math.Round(1.13451, 2);
Inside an if statement
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I need someone to give me an idea on how to go on about this problem.Using a loop to calculate the fraction , There is no common value.I want to get the sum
Eg for fraction :
1 1/5 1/10 1/15 1/20 … 1/290 1/295 1/300
code snippet:-
int sum=0;
for(int i=1;i<=60 ;i++)
{
int sum=1
}
These sort of problems are actually surprisingly non-trivial due to issues with working with floating point, and decimal types for that matter.
Accepting that you want a loop solution for this (a closed form solution for n terms does exist), first note that your series can be written as
1 + 1/5(1 + 1/2 + 1/3 + ... + 1/60)
Then note that a good rule of thumb when working with floating point types is to add the small terms first.
So an algorithm would be of the form
double sum = 0.0;
for (int i = 60; i >= 1; --i){
sum += 1.0 / i;
}
sum = sum / 5 + 1;
Note the 1.0 in the numerator; that's there to defeat integer division.
Reference: Is floating point math broken?
͏Since you asked for a hint:
float sum = 1.0;
for (int i = 5; i <= ??; i += ??) {
sum += 1.0/i;
}
What goes in place of the ??s?
try this code:
double sum=1;
for(int i=5; i<=300; i+=5)
sum += (double) 1 / i;
The value of sum will be 1.93597408259035
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I am using Kinect v2 which contains the following CameraSpacePoint struct:
public struct CameraSpacePoint : IEquatable<CameraSpacePoint>
{
public float X;
public float Y;
public float Z;
}
The CameraSpacePoint also contains few methods Equals, GetHashCode etc, which are not shown above to keep the post clean and short.
Well, I define cameraSpacePoints in class constructor as follows:
IntPtr cameraSpacePoints = Marshal.AllocHGlobal(512 * 424 * 4 * 3);
Below is the explanation of above memory allocation:
512: width
424: height
4: bytes needed for single 'float'
3: total three variables i.e., 'X', 'Y' and 'Z'
Later, I copied values to cameraSpacePoints using CoordinateMapper as follows:
coordinateMapper.MapDepthFrameToCameraSpaceUsingIntPtr(depthFrameData,
512 * 424 * 2,
cameraSpacePoints,
512 * 424 * 4 * 3);
It seems perfect. Now I want to get the values from cameraSpacePoints. So I used following code inside unsafe block:
float* cameraSpacePoint = (float*)cameraSpacePoints;
for (var index = 0; index < 512 * 424; index++)
{
float X = cameraSpacePoint[index];
float Y = cameraSpacePoint[index + 1];
float Z = cameraSpacePoint[index + 2];
}
It doesn't seem working which I realized while visualizing it. It appears to me that there is some confusion while accessing elements from cameraSapacePoints using IntPtr. What is missing here? Any suggestions, please?
In your initial code, you are casting the IntPtr (which points to an array[] of CameraSpacePoint) to a raw float pointer. If you interpret the IntPtr as raw floats, since you are handling 3 points at a time (x, y and z), you'll need to increment the loop by 3 floats each time, e.g. (I've renamed variables for clarity):
var floats = (float*)cameraSpacePoints;
for (var index = 0; index < 512 * 424; index+=3)
{
var x = floats[index];
var y = floats[index + 1];
var z = floats[index + 2];
var myCameraSpacePoint = new CameraSpacePoint
{
X = x,
Y = y,
Z = z
};
// use myCameraSpacePoint here
}
But that's a horribly inefficient way of handling the data, given that the data was originally a CameraSpacePoint in any event. Much better would just be to cast the struct directly back to the actual type:
var cameraSpacePoints = (CameraSpacePoint*)cameraSpacePoints;
for (var index = 0; index < 512 * 424; index++)
{
var cameraSpacePoint = cameraSpacePoints[index];
// Do something with cameraSpacePoint
}
By casting to the correct type (CameraSpacePoint), we're also improving the robustness of the code - e.g. if, in future, additional fields are added to a new version of CameraSpacePoint, then a recompile of your code against the new version will again work, whereas accessing the floats directly would break the encapsulation and make maintenance difficult.
The reason why we no longer need to increment the loop by 3, is because when we use the subscript / index operation on cameraSpacePoints[index], is that the compiler knows to find element n at an offset of n * sizeof(CameraSpacePoint) after the position of the initial cameraSpacePoints[0]. And sizeof(CameraSpacePoint) is the size of 3 floats.