So I wrote a Quadratic formula program in C#, how do I take the quadratic formula program and modify it so that the program correctly displays the number of solutions.
if there are two solutions,
(x - x1)(x - x2) = 0
if there is only one solution,
(x - x0)^2 = 0
if there are no solutions,
No Solution.
This is the program, if someone could show the solution to this for me that would be wonderful, I'm really stuck on how to do it.
using System;
namespace quadraticequation
{
class MainClass
{
public static void Main(string[] args)
{
Console.WriteLine("Enter a number for a"); //ask the user for information
double a = double.Parse(Console.ReadLine()); //Gets a from the user
Console.WriteLine("Enter a number for b"); //asks the user for information
double b = double.Parse(Console.ReadLine()); //Gets b from the user
Console.WriteLine("Enter a number for c"); //asks the user for information
double c = double.Parse(Console.ReadLine()); //Gets c from the user
//double.Parse --> is used to convert a number or string to a double.
//Console.ReadLine() --> is used to take the input from the user.
//We call a function here
Quadratic(a, b, c);
}
//We need to create a new function
public static void Quadratic(double a, double b, double c)
{
double deltaRoot = Math.Sqrt(b * b - 4 * a * c); //Math.Sqrt takes the square root of the number
if (deltaRoot >= 0) // we use an if statement here to handle information
{
double x1 = (-b + deltaRoot) / 2 * a; //We write the information for x1 here
double x2 = (-b - deltaRoot) / 2 * a; //We write the information for x2 here
Console.WriteLine("x1 = " + x1 + " x2 = " + x2); //we use this to write the roots
}
else // we use an else statement so that we dont return an error when there are no roots
{
Console.WriteLine("There are no roots");
}
}
}
}
I think you have to review your second degree formula solution-skills. You write:
double deltaRoot = Math.Sqrt(b * b - 4 * a * c);
But the test is actually whether b2-4×a×c is larger than or equal to zero: indeed that is actually why we check it: because we cannot take the square root of a negative number (yeah there exist complex numbers that can take the square root of a negative number, but let's ignore that for now).
So the solution is to write it like:
public static void Quadratic(double a, double b, double c) {
double delta = b*b-4*a*c; //only delta
if (delta > 0) {
double deltaRoot = Math.Sqrt(delta);
double x1 = (-b + deltaRoot) / (2 * a); //We write the information for x1 here
double x2 = (-b - deltaRoot) / (2 * a); //We write the information for x2 here
Console.WriteLine("x1 = " + x1 + " x2 = " + x2); //we use this to write the roots
} else if(delta == 0) {
double x1 = -b/(2*a);
Console.WriteLine("x1 = " + x1); //we use this to write the roots
} else {
Console.WriteLine("There are no roots");
}
}
You also have to write (-b + deltaRoot) / (2*a) (with (2*a)), otherwise you will multiply (-b + deltaRoot) / 2 with a instead.
A final note is that equality comparisons with floating points is very tricky so delta == 0 will often fail since the result can be something 1e-20-ish, which is simply an error when performing floating point arithmetic. So it is perhaps better to use a small range of values.
This gives:
csharp> MainClass.Quadratic(1,1,1);
There are no roots
csharp> MainClass.Quadratic(1,1,0);
x1 = 0 x2 = -1
csharp> MainClass.Quadratic(1,0,0);
x1 = 0
Related
Good morning,
I'm so stuck solving this problem. Here's content of the task:
"Create a static method double SolvingSquare (double a, double b, double c,? x1,? x2) returning the number of solutions, and in x1 and x2 possible solutions."
I already made it to return number of solutions, but I don't know how to return x1 and x2 after already returning number of solutions. I tried to write "? x1, ? x2" arguments, but then red underline appears. I'm so confused with this one.
static void Main(string[] args)
{
Console.WriteLine($"Number of Solutions: {Method.SolveSquare(1, 3, 1)}");
}
class Method
{
public Method()
{}
public static double SolveSquare(double a, double b, double c)
{
double delta = (b * b) - (4 * a * c);
double squareDelta = Math.Sqrt(delta);
double x1 = (-b + squareDelta) / (2 * a);
double x2 = (-b - squareDelta) / (2 * a);
if(delta < 0)
{
return 0;
} return (delta == 0) ? 1 : 2;
}
In order to not spoil this completely, but still help you:
You probably want something like this ...
double solutions = Solve(1,3,1, out double x1, out double x2);
Console.WriteLine($"We have {solutions} solutions, which are x1={x1} and x2={x2}");
// And the Solve Function:
public static double Solve(double a, double b, double c, out double x1, out double x2)
{
// Implementation up to you, but somewhere must be:
x1 = // Solution for x1;
x2 = // Solution for x2;
}
Another unrelated tip: if delta is <0, you don't need to do the rest of the calculations, actually. You can set x1 and x2 to double.NaN and return 0.
https://dotnetfiddle.net/VJch0u
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I was trying to calculate the result of a second degree equation using C#, but i get the result NaN. Can someone check my code to locate the error ?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace desafio2_2
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please insert the values that multiply x², x and the independent term respectively: ");
float a = float.Parse(Console.ReadLine());
float b = float.Parse(Console.ReadLine());
float c = float.Parse(Console.ReadLine());
double bhaskarap1 = (Math.Pow(b, 2)) + (- 4 * a * c);
double raiz1 = (-b + Math.Sqrt(bhaskarap1)) / (2 * a);
double raiz2= (-b - Math.Sqrt(bhaskarap1)) / (2 * a);
Console.WriteLine(raiz1);
Console.WriteLine(raiz2);
}
}
}
It may be possible that the quadratic equation has no real roots. In this case the discriminant will be negative.
Math.Sqrt(x) returns NaN when when x is negative. You should test the discriminant for negative number before you call the square root function.
static void Main(string[] args)
{
Console.WriteLine("Please insert the values that multiply x², x and the independent term respectively: ");
float a = float.Parse(Console.ReadLine());
float b = float.Parse(Console.ReadLine());
float c = float.Parse(Console.ReadLine());
double bhaskarap1 = (Math.Pow(b, 2)) + (- 4 * a * c);
if (bhaskarap1 < 0)
{
Console.WriteLine("There are no real solutions.");
return;
}
double raiz1 = (-b + Math.Sqrt(bhaskarap1)) / (2 * a);
double raiz2= (-b - Math.Sqrt(bhaskarap1)) / (2 * a);
Console.WriteLine(raiz1);
Console.WriteLine(raiz2);
}
argument of sqrt method must be positive.
I would check for NaN using a ternary operator like I did below to handle the case of a negative value for sqrt.
float a = 4.0f, b = 7.0f, c = -3.0f;
double my_var = ((Math.Pow(b, 2)) + (-4 * a * c));
Console.WriteLine(my_var);
Console.WriteLine(((-b + Math.Sqrt(-1 * my_var)) / (2 * a)));
double temp = (-b + Math.Sqrt(my_var)) / (2 * a);
double raiz1 = temp.CompareTo(Double.NaN) < 1 ? 0.00 : temp;
temp = (-b + Math.Sqrt(-1 * my_var)) / (2 * a);
double raiz2 = temp.CompareTo(Double.NaN) < 1 ? 0.00 : temp;
Console.WriteLine($"Raiz1: {raiz1}\tRaiz2: {raiz2}");
Output:
97
NaN
Raiz1: 0.356107225224513 Raiz2: 0
The roots of the second degree equations are complex numbers in general case, e.g.
x**2 + 1 = 0
That's why I suggest using Complex, not float:
...
using System.Numerics;
...
// float.Parse - if you want to allow just real coefficients
Complex a = float.Parse(Console.ReadLine());
Complex b = float.Parse(Console.ReadLine());
Complex c = float.Parse(Console.ReadLine());
Complex bhaskarap1 = b * b - 4 * a * c;
Complex raiz1 = (-b + Complex.Sqrt(bhaskarap1)) / (2 * a);
Complex raiz2 = (-b - Complex.Sqrt(bhaskarap1)) / (2 * a);
Console.WriteLine(raiz1);
Console.WriteLine(raiz2);
How can I use a Fast Magnitude calculation for 3 values (instead of using square root)? (+/- 3% is good enough)
public void RGBToComparison(Color32[] color)
{
DateTime start = DateTime.Now;
foreach (Color32 i in color)
{
var r = PivotRgb(i.r / 255.0);
var g = PivotRgb(i.g / 255.0);
var b = PivotRgb(i.b / 255.0);
var X = r * 0.4124 + g * 0.3576 + b * 0.1805;
var Y = r * 0.2126 + g * 0.7152 + b * 0.0722;
var Z = r * 0.0193 + g * 0.1192 + b * 0.9505;
var LB = PivotXyz(X / 95.047);
var AB = PivotXyz(Y / 100);
var BB = PivotXyz(Z / 108.883);
var L = Math.Max(0, 116 * AB - 16);
var A = 500 * (LB - AB);
var B = 200 * (AB - BB);
totalDifference += Math.Sqrt((L-LT)*(L-LT) + (A-AT)*(A-AT) + (B-BT)*(B-BT));
}
totalDifference = totalDifference / color.Length;
text.text = "Amount of Pixels: " + color.Length + " Time(MilliSeconds):" + DateTime.Now.Subtract(start).TotalMilliseconds + " Score (0 to 100)" + (totalDifference).ToString();
RandomOrNot();
}
private static double PivotRgb(double n)
{
return (n > 0.04045 ? Math.Pow((n + 0.055) / 1.055, 2.4) : n / 12.92) * 100.0;
}
private static double PivotXyz(double n)
{
return n > 0.008856 ? CubicRoot(n) : (903.3 * n + 16) / 116;
}
private static double CubicRoot(double n)
{
return Math.Pow(n, 1.0 / 3.0);
}
This is the important part: totalDifference += Math.Sqrt((L-LT)*(L-LT) + (A-AT)*(A-AT) + (B-BT)*(B-BT));
I know there are FastMagnitude calculations online, but all the ones online are for two values, not three. For example, could i use the difference between the values to get a precise answer? (By implementing the difference value into the equation, and if the difference percentage-wise is big, falling back onto square root?)
Adding up the values and iterating the square root every 4 pixels is a last resort that I could do. But firstly, I want to find out if it is possible to have a good FastMagnitude calculation for 3 values.
I know I can multi-thread and parllelize it, but I want to optimize my code before I do that.
If you just want to compare the values, why not leave the square root out and work with the length squared?
Or use the taylor series of the square root of 1+x and cut off early :)
I have this function wrote in C# to calc the sin(x). But when I try with x = 3.14, the printed result of sin X is NaN (not a number),
but when debugging, its is very near to 0.001592653
The value is not too big, neither too small. So how could the NaN appear here?
static double pow(double x, int mu)
{
if (mu == 0)
return 1;
if (mu == 1)
return x;
return x * pow(x, mu - 1);
}
static double fact(int n)
{
if (n == 1 || n == 0)
return 1;
return n * fact(n - 1);
}
static double sin(double x)
{
var s = x;
for (int i = 1; i < 1000; i++)
{
s += pow(-1, i) * pow(x, 2 * i + 1) / fact(2 * i + 1);
}
return s;
}
public static void Main(String[] param)
{
try
{
while (true)
{
Console.WriteLine("Enter x value: ");
double x = double.Parse(Console.ReadLine());
var sinX = sin(x);
Console.WriteLine("Sin of {0} is {1}: " , x , sinX);
Console.ReadLine();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
It fails because both pow(x, 2 * i + 1) and fact(2 * i + 1) eventually return Infinity.
In my case, it's when x = 4, i = 256.
Note that pow(x, 2 * i + 1) = 4 ^ (2 * 257) = 2.8763090157797054523668883052624395737887631663 × 10^309 - a stupidly large number which is just over the max value of a double, which is approximately 1.79769313486232 x 10 ^ 308.
You might be interested in just using Math.Sin(x)
Also note that fact(2 * i + 1) = 513! =an even more ridiculously large number which is more than 10^1000 times larger than the estimated number of atoms in the observable universe.
When x == 3.14 and i == 314 then you get Infinity:
?pow(-1, 314)
1.0
?pow(x, 2 * 314 + 1)
Infinity
? fact(2 * 314 + 1)
Infinity
The problem here is an understanding of floating point representation of 'real' numbers.
Double numbers while allowing a large range of values only has a precision of 15 to 17 decimal digits.
In this example we are calculating a value between -1 and 1.
We calculate the value of the sin function by using the series expansion of it which is basically a the sum of terms. In that expansion the terms become smaller and smaller as we go along.
When the terms have reached a value less than 1e-17 adding them to what is already there will not make any difference. This is so because we only have 52 bit of precision which are used up by the time we get to a term of less than 1e-17.
So instead of doing a constant 1000 loops you should do something like this:
static double sin(double x)
{
var s = x;
for (int i = 1; i < 1000; i++)
{
var term = pow(x, 2 * i + 1) / fact(2 * i + 1);
if (term < 1e-17)
break;
s += pow(-1, i) * term;
}
return s;
}
I just wrote my first C# program.
It's a simple piece of code which solves quadratic equations.
It works with some functions (such as -6x2-6x+12) perfectly, while with others, (4x2-20x+25) it exhibits what I suspect are rounding errors.
I'm completely new to C#, and I can't see an problems; would someone be able to help me debug this code?
namespace ConsoleApplication {
class Program {
static int ObtainInput(string prompt, bool canBeZero) {
double a = ObtainInput("A? ", false);
double b = ObtainInput("B? ", true);
double c = ObtainInput("C? ", true);
double d, x1, x2;
while (true) {
Console.Write(prompt);
string input = Console.ReadLine();
int result;
bool success = int.TryParse(input, out result);
if (success && (canBeZero || result != 0))
return result;
Console.WriteLine("Invalid input!");
}
// Calculating a discriminant
d = b * b - 4 * a * c;
if (d == 0) {
x1 = -b / (2 * a);
Console.WriteLine("The only solution is x={0}.", x1);
Console.ReadLine();
}
// If d < 0, no real solutions exist
else if (d < 0) {
Console.WriteLine("There are no real solutions");
Console.ReadLine();
}
// If d > 0, there are two real solutions
else {
x1 = (-b - Math.Sqrt(d)) / (2 * a);
x2 = (-b + Math.Sqrt(d)) / (2 * a);
Console.WriteLine("x1={0} and x2={1}.", x1, x2);
Console.ReadLine();
}
}
}
}
I just wrote my first C# program.
Awesome. Now would be a great time to not get into bad habits:
entA: Console.Write("a?");
try { a = Convert.ToInt32(Console.ReadLine()); }
catch
{ /*If a=0, the equation isn't quadratic*/
Console.WriteLine("Invalid input");
goto entA;
}
Problems abound. First off, use int.TryParse, rather than putting a try-catch around something that can fail.
Second, the comment does not match the action of the code. The code determines if the result is an integer; the comment says that it checks for zero.
Third, do not use a goto when what you are attempting to represent is a loop.
Fourth, look at all that duplicated code! You have the same code repeated three times with minor variations.
Make yourself a helper method:
static int ObtainInput(string prompt, bool canBeZero)
{
while(true) // loop forever!
{
Console.Write(prompt);
string input = Console.ReadLine();
int result;
bool success = int.TryParse(input, out result);
if (success && (canBeZero || result != 0))
return result;
Console.WriteLine("Invalid input!");
}
}
And now your mainline is:
int a = ObtainInput("A? ", false);
int b = ObtainInput("B? ", true);
int c = ObtainInput("C? ", true);
Your bug though is here:
x1 = x2 = -b / (2 * a);
You do the arithmetic in integers, and then convert to doubles. That is, you do the division, round to the nearest integer, and then convert to double. Do it in doubles (or, less likely, in decimals) from the start. It should be:
double a = ObtainInput("A? ", false);
double b = ObtainInput("B? ", true);
double c = ObtainInput("C? ", true);
That is, a, b, and c should not ever be integers.
You're doing integer division when assigning to x1 and x2; (you can just change the 2 to 2.0 to change it to double division and get a double result)
It might also make sense to change your a,b,c, and d values to double which will also get past the problem, and allow people to enter non-int values for the coefficients.
int a, b, c;
int d;
first of all, try to use double instead of int, since 1/3 = 0 using integers.