Iteration of an Unknown Number in C# - c#

Let's say I have a formula which contains a variable that user has to guess. But at the end of formula, that variable is calculated again and if the first one and second one doesn't match, formulation has to be solved again with a new value. Shortly assume that I have a formula like this (mine is much more complex and longer than this);
double y1 = Convert.ToDouble(txtboxPredefinedY.Text);
double x, z, Ort;
double y2 = 0;
while (y1 != y2)
{
x = (Math.Pow(y1, 2)) + 10;
z = (y1 - 2) / 3;
y2 = (x / z);
Ort = (y2 + y1)/2;
y1 = Ort;
if (y1 == y2)
break;
}
txtboxResult.Text = r.ToString();
So the y1 variable I defined first has to match the last variable y2. To achieve this I calculate the whole formula and find a new y1, re-calculate formula.
I want to define a y1 value and let the application correct me. For example this code should return me a value of 3.3158. If first input is 3.3158 than y1 becomes equal to y2.
I couldn't use while iteration correctly. How can I fix this? Or maybe, how should I build my while block to give me exact equation?

When working with Double you should compare with tolerance:
double y1 = Convert.ToDouble(txtboxPredefinedY.Text);
double x, z, Ort;
double y2 = 0;
double tolerance = 0.001;
while (Math.Abs(y1 - y2) >= tolerance) {
x = (Math.Pow(y1, 2)) + 10;
z = (y1 - 2) / 3;
y2 = (x / z);
Ort = (y2 + y1)/2;
y1 = Ort;
}
Comparisons like y1 != y2 as well as y1 == y2 may fail because of round-up errors.

Related

How to get the locations of all the points on a line WP8.1 Silverlight c#

I am drawing a line onto the canvas, by giving it a starting and ending point. Now I want to get the X and Y location of each point of that line. how can I do that?
Line line = new Line();
line.Visibility = System.Windows.Visibility.Visible;
line.StrokeThickness =1;
line.X1 = x[1];
line.X2 = y[1];
line.Y1 = x[i-1]/4;
line.Y2 = y[i - 1] / 4;
MyIP.Children.Add(line);
This is simple math. You know the starting and ending point of the line, meaning you can calculate any point you want on that line, by using the equation of the line. The way to get the equation is
y = y1 + [(y2 - y1) / (x2 - x1)] * (x - x1)
You know 2 points: (x1, y1) and (x2, y2)
In the end you'll get something in the form of
y = Ax + B
Meaning that for every x, you can calculate y, as A & B are constants.
So you could simply loop through all the x values, and increment by whatever granularity you want or need, to get the appropriate y values, and you'll end up with a set of (x, y) values
for (double i = x1; i <= x2; i+=0.2)
{
var x = i;
var y = (A*x)+B;
// now you have one pair of x, y
}

Blending/smooth-shading material

I'm creating and drawing a triangle mesh in wpf c# using GeometryModel3D. I've been trying to figure out how to create a smooth shading over the triangles, like the classic openGL smooth shaded triangle.
I would like to define a colour for each vertex, and then having the colours interpolated over the face, like this, assuming the three colour where red, green and blue.
I assumed I would need to use a brush, but I haven't been able to figure out how.
So any help would be appreciated, or any pointer to a guide that shows me how to achieve this.
EDIT:
I've looked at Triangular Gradient in WPF3D, which seems to answer the question partly, just using xaml.
Unfortunatly it seems like it need equilateral triangles.
2nd EDIT
The answer above, uses the RadialGradientBrush. Is the RadiusXand RadiusY used to make it elliptic instead of circular?
3rd EDIT
Okay, I'm fairly sure I can use the RadialGradientBrush. What I think I can do is, find the center of the circumcircle of the triangles, and create a RadialGradientBrush with RadiusX and RadiusY equal to the radius if the circumcircle. I would then move the focal point of the RadialGradientBrush to the vertices with GradientOrigin.
GradientOrigin takes two doubles X,Y as the center, with both of them being in the interval [0,1]. From what I can read is X = 0.0 is the left side and X = 1.0 is the right side and Y = 0.0 is the top and Y = 1.0 is the bottom. What I can't figure out, is this mapping [0,1]x[0,1] to a circle, or is it a square? The mapping from the vertices of the triangle to [0,1]x[0,1], depends on what shape this interval represents.
Have you heard of Helix 3D Toolkit for WPF ?
I didn't go as far as you'd like but I guess it is possible by looking at the Surface Demo example :
There are surely libraries for that, but to give some simple way, searching through some google,http://www.geeksforgeeks.org/check-whether-a-given-point-lies-inside-a-triangle-or-not/
computing the distance from corners, gives info about the smooth color. Checking if point is in triangle.
float area(int x1, int y1, int x2, int y2, int x3, int y3)
{
return (float)Math.Abs((x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)) / 2.0);
}
bool isInside(int x1, int y1, int x2, int y2, int x3, int y3, int x, int y)
{
/* Calculate area of triangle ABC */
float A = area(x1, y1, x2, y2, x3, y3);
/* Calculate area of triangle PBC */
float A1 = area(x, y, x2, y2, x3, y3);
/* Calculate area of triangle PAC */
float A2 = area(x1, y1, x, y, x3, y3);
/* Calculate area of triangle PAB */
float A3 = area(x1, y1, x2, y2, x, y);
/* Check if sum of A1, A2 and A3 is same as A */
return (A == A1 + A2 + A3);
}
for (int ii = 5; ii < 100; ii++)
{
for (int jj = 5; jj < 100; jj++)
{
int distanceRed =0, distanceGreen =0,distanceBlue =0;
if (isInside(30, 50, 30, 90, 20, 70, ii, jj))
{
distanceRed = (int)Math.Sqrt(((ii - 30) * (ii - 30) + (jj - 50) * (jj - 50)));
distanceGreen = (int)Math.Sqrt(((ii - 30) * (ii - 30) + (jj - 90) * (jj - 90)));
distanceBlue = (int)Math.Sqrt(((ii - 20) * (ii - 20) + (jj - 70) * (jj - 70)));
}
else
{
distanceRed = 0; distanceGreen = 0; distanceBlue = 0;
}
ptr[(((int)jj) * 3) + ((int)ii) * stride] = (byte)(distanceRed % 256);
ptr[(((int)jj) * 3) + ((int)ii) * stride + 1] = (byte)(distanceGreen % 256);
ptr[(((int)jj) * 3) + ((int)ii) * stride + 2] = (byte)(distanceBlue % 256);
}
}
gives the result:
Couldnt fit the red. Maybe the modulo is wrong here.
Also the sqrt is inefficient.

Run-Time Calculation

i am working on Windows Forms Application. i have three buttons. i have written a method that calculates a new location for each button. but i had some errors (explained after the code). the method is:
Random random = new Random();
public int SetPointLocation()
{
int x1 = x2 - 20;
int x2;
int x3 = x2 + 20;
int y1 = y2 - 1;
int y2 = random.Next(0, 2);
int y3 = y2 + 1;
return x2 = (((x3 - x1) * (y2 - y1)) / y3 - y1) + x1;
}
the errors i get :
Cannot use local variable 'x2' before it is declared.
Cannot use local variable 'y2' before it is declared.
so i rearranged the method's block:
Random random = new Random();
public int SetPointLocation()
{
int x2;
int x1 = x2 - 20;
int x3 = x2 + 20;
int y2 = Convert.ToInt32((picBox.Name).Remove(0, 10));
int y1 = y2 - 1;
int y3 = y2 + 1;
return x2 = (((x3 - x1) * (y2 - y1)) / y3 - y1) + x1;
}
now the errors i get:
"Use of unassigned local variable 'x2'".
The formula i've used is the way of finding the median from a Frequency tables "Statistics".
but 'x2' is unknown and i want to calculate it at run-time, but because 'x2' has no value, i can't set 'x1', and 'x3'. What is the solution for this problem?!
Simply use
int x2 = 0;
Everything needs to be initialized before it can be used. This is a requirement of the language.
Not too close related, but hits it anyways: SO.
It sounds like you really just want to pass x2 in as a parameter. You can then call the function when you do know what x2 is supose to be.
Random random = new Random();
public int SetPointLocation(int x2)
{
int x1 = x2 - 20;
int x3 = x2 + 20;
int y2 = Convert.ToInt32((picBox.Name).Remove(0, 10));
int y1 = y2 - 1;
int y3 = y2 + 1;
// Just return what x2 needs to be
return (((x3 - x1) * (y2 - y1)) / y3 - y1) + x1;
}
x2 is not set before using it.
Random random = new Random();
public int SetPointLocation()
{
int x2; // <- here' the problem
int x1 = x2 - 20;
...
give a value to x2:
x2 = 123;
using a uninitialized variable is not allowed in C#.
the compiler should tell you the place where the error is.

Value of expression doesn't change

I'm trying to move the cursor using linear interpolation. My problem is that the value of y0 + (y1 - y0) * ((x - x0) / (x1 - x0)) never changes despite the fact that x changes. I can't figure out what I'm missing.
public void MoveCursor(int x1, int y1)
{
int y, y0, x, x0;
y0 = Cursor.Position.Y;
x0 = Cursor.Position.X;
for (x = x0; x > x1; x--)
{
y = y0 + (y1 - y0) * ((x - x0) / (x1 - x0));
this.Cursor = new Cursor(Cursor.Current.Handle);
Cursor.Position = new Point(x,y);
Cursor.Clip = new Rectangle(this.Location, this.Size);
Console.Out.WriteLine("X:{0} Y:{1}", x, y);
System.Threading.Thread.Sleep(100);
}
}
Try using floats:
y = (int)(y0 + (float)(y1 - y0) * (x - x0) / (x1 - x0));

Line rasterisation: Cover all pixels, regardless of line gradient?

Basically, I want to use a line algo to determine which cells to check for collisions for my raycaster.
Bresenham isn't great for this as it uses a unified-thickness approach, meaning that it ignores cells that aren't at least half-covering the line. Not great at all, because it means that some segments of my line aren't being checked for intersections with the cells, leading to errors.
I can't seem to find any "thick-line" algorithms, can anyone help me find one?
Green: What I would like.
Red: What I currently have and don't want.
I had exactly the same problem as you and found an very simple solution. Usually, Bresenham has two consecutive if's to determine whether it should increase the coordinate for the two dimensions:
public void drawLine(int x0, int y0, int x1, int y1, char ch) {
int dx = Math.abs(x1 - x0), sx = x0 < x1 ? 1 : -1;
int dy = -Math.abs(y1 - y0), sy = y0 < y1 ? 1 : -1;
int err = dx + dy, e2; // error value e_xy
for (;;) {
put(x0, y0, ch);
if (x0 == x1 && y0 == y1) break;
e2 = 2 * err;
// horizontal step?
if (e2 > dy) {
err += dy;
x0 += sx;
}
// vertical step?
if (e2 < dx) {
err += dx;
y0 += sy;
}
}
}
Now all you have to do is to insert an else before the second if:
public void drawLineNoDiagonalSteps(int x0, int y0, int x1, int y1, char ch) {
int dx = Math.abs(x1 - x0), sx = x0 < x1 ? 1 : -1;
int dy = -Math.abs(y1 - y0), sy = y0 < y1 ? 1 : -1;
int err = dx + dy, e2;
for (;;) {
put(x0, y0, ch);
if (x0 == x1 && y0 == y1) break;
e2 = 2 * err;
// EITHER horizontal OR vertical step (but not both!)
if (e2 > dy) {
err += dy;
x0 += sx;
} else if (e2 < dx) { // <--- this "else" makes the difference
err += dx;
y0 += sy;
}
}
}
Now the algorithm doesn't change both coordinates at once anymore.
I haven't thoroughly tested this but it seems to work pretty well.
This thread old, but I thought it'd be worth putting this on the Internet:
// This prints the pixels from (x, y), increasing by dx and dy.
// Based on the DDA algorithm (uses floating point calculations).
void pixelsAfter(int x, int y, int dx, int dy)
{
// Do not count pixels |dx|==|dy| diagonals twice:
int steps = Math.abs(dx) == Math.abs(dy)
? Math.abs(dx) : Math.abs(dx) + Math.abs(dy);
double xPos = x;
double yPos = y;
double incX = (dx + 0.0d) / steps;
double incY = (dy + 0.0d) / steps;
System.out.println(String.format("The pixels after (%d,%d) are:", x, y));
for(int k = 0; k < steps; k++)
{
xPos += incX;
yPos += incY;
System.out.println(String.format("A pixel (%d) after is (%d, %d)",
k + 1, (int)Math.floor(xPos), (int)Math.floor(yPos)));
}
}
Without loss of generality, assume x2 >= x1, then
int x = floor(x1);
int y = floor(y1);
double slope = (x2 - x1) / (y2 - y1);
if (y2 >= y1) {
while (y < y2) {
int r = floor(slope * (y - y1) + x1);
do {
usepixel(x, y);
++x;
} while (x < r);
usepixel(x, y);
++y;
}
}
else {
while (y > y2) {
int r = floor(slope * (y - y1) + x1);
do {
usepixel(x, y);
++x;
} while (x < r);
usepixel(x, y);
--y;
}
}
The floor calls can probably be written just as a cast-to-integer.
There is an interesting article available in GPU Gems, maybe it can help you: Chapter 22. Fast Prefiltered Lines
What about Bresenham with an additional constraint that no diagonal moves are allowed: Generate the points with the traditional algorithm, then as a post-processing step insert extra steps needed to make only orthogonal movements.
You could find all the intersections your ray has with the horizontal grid lines, and then mark all the cells on a row that either have an intersection point on one side, or are between the two cells with the intersections on the row.
Finding the intersections can be done by starting from the origin, advancing the point to the first intersection (and marking the cells in the process), finding out the vector that takes you from an intersection to the next (both these operations are basic similar triangles (or trig)) and then advancing column by column until you've gone far enough. Advancing column by column involves one vector addition per column, and a small loop to fill in the cells between the ones with intersections. Replace "mark" with "process" if you're processing the cells on the fly - this algorithm is guaranteed to mark each cell only once.
The same could be done with the vertical lines, but grids are generally stored in horizontal slices so I chose that. If you're using trig, you'll need to handle straight horizontal lines with a special case.
By the way, as far as I know, this is how old grid-based raycaster "3D" games (like Wolfenstein 3D) were done. I first read about this algorithm from this book, eons ago.

Categories