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);
Related
I am working on 2 class simple perceptron problem. My project work getting user mouse click from GUI panel and make classification. Class 1 expected output: 1 and Class 2 expected output -1. My problem is discrete perceptron working fine but continuous perceptron after one point stop decrease error. I don't know what I am doing wrong. I look so much code and source.
My formulas;
E=1/2 Σ(d-o)^2
f(net)=(2/(1+ⅇ^(-net)))-1
ΔW=n(d-o)(1-o^2)y
like this.
d: Expected output,
net: weight*input sum,
y: input matrix ([x1 x2 -1]) and
o: Actual output.
Code for continuous perceptron below;
while (totalError > Emax)
{
totalError = 0;
for(i=0; i<point.Count; i++)
{
double x1 = point[i].X1;
double x2 = point[i].X2;
double net = (x1 * w0) + (x2 * w1) + (x0 * w2);
double o = (2 / (1 + Math.Exp(-net))) - 1;
double error = Math.Pow(point[i].Class - o, 2);
w0 += (x1 * c * (point[i].Class - o) * (1 - Math.Pow(o, 2))) / 2;
w1 += (x2 * c * (point[i].Class - o) * (1 - Math.Pow(o, 2))) / 2;
w2 += (x0 * c * (point[i].Class - o) * (1 - Math.Pow(o, 2))) / 2;
totalError += error;
}
totalError = totalError / 2;
ErrorShow(cycle, totalError);
objGraphic.Clear(Color.White);
DrawSeperationLine();
cycle++;
}
Emax=0.001 selected. Project working like this. You can see it not correct line location. Class 1 is blue and class 2 red.
I think problem in for loop.
Console Output of Code:
Edit:
After discuss with #TaW (Thanks for showing road), I find out my problem in output (activation function). It always return 1 or -1. After that in weight change function [1-Math.Pow(o,2)] part return 0 and that make weight change equal 0. So my question how can I solve this problem. Type casting not work.
My question's solution is using normalization. For normalization I use standard deviation. Standart deviation code is below;
for(i=0;i<point.Count;i++){
x1 += point[i].X1;
x2 += point[i].X2;
}
meanx1 = x1 / point.Count;
meanx2 = x2 / point.Count;
for(i=0;i<point.Count;i++){
totalX1 += Math.Pow(point[i].X1 - meanx1, 2);
totalX2 += Math.Pow(point[i].X2 - meanx2, 2);
}
normX1 = totalX1 / (point.Count - 1);
normX2 = totalX2 / (point.Count - 1);
normX1 = normX1 / 100;
normX2 = normX2 / 100;
The last division is used to decrease the value.
I am trying to calculate the delta of a number using a formula of bhaskara and delta but it is giving NaN in the message box
//Variables declaration
int a = 800, b = 500, c = 350;
double delta, a1, a2;
//Formulas
delta = (b*b) - (4*a*c);
a1 = (-b + Math.Sqrt(delta)) / (2 * a);
a2 = (-b - Math.Sqrt(delta)) / (2 * a);
//Output
MessageBox.Show(a1.ToString());
MessageBox.Show(a2.ToString());
The value of delta is -870000.
That's not a value you can take the square root of (and get a real number anyway).
From the Math.Sqrt docs:
As Broots said Math.sqrt of negative number will return NaN. There is a Complex struct that should do what you need:
Complex c = Complex.Sqrt(-25); // has a value of approximately 0 + 5i
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
I have geometrical algorithms and im struggling with floating point inaccuracies.
For example, I'm calculating wether a point lies on the left/right/on a plane (C#):
const double Epsilon = 1e-10;
internal double ComputeDistance(Vector3D v)
{
Vector3D normal = Plane.Normal;
Vertex v0 = Plane.Origin;
double a = normal.X;
double b = normal.Y;
double c = normal.Z;
double d = -(a * v0.X + b * v0.Y + c * v0.Z);
return a * v.X + b * v.Y + c * v.Z + d;
}
internal string DistanceSign(Vector3D v)
{
var distance = ComputeDistance(v);
return (distance > Epsilon ? "left" : (distance < -Epsilon ? "right" : "on"));
}
As shown in the code, I use a fixed Epsilon value.
But I don't trust this fixed epsilon because I don't know the size of the floating point error. If the fp error is bigger than my epsilon interval, then my algorithm will fail.
How can I make it robust? I have searched on the internet but haven't found a solution so far. I have read "What Every Computer Scientist Should Know About Floating-Point Arithmetic", it describes why fp errors occur but not how to solve them practically.
Edit
Here is a shewchuk predicate that doesn't seem work:
double[] pa = {0, 0};
double[] pb = {2 * Double.Epsilon, 0};
double[] pc = { 0, Double.Epsilon };
Assert.IsTrue(GeometricPredicates.Orient2D(pa, pb, pc) > 0);
The assertion fails because Orient2D return 0. The code is here
Edit2
Shouldn't it be possible to calculate an error bound by using the machine epsilon? According to wikipedia, the machine epsilon is an upper bound due to rounding. For double, it is 2^−53. So as I take it, when I have an arithmetic calculation:
double x = y + z
then the maximum error should be 2^−53. Shouldn't this fact enable the possiblity to calculate an appropriate epsilon? So two rewrite my method:
double const Machine_Eps = 1.11022302462516E-16 // (2^-53)
double Epsilon = Machine_Eps;
internal double ComputeDistance(Vector3D v)
{
Vector3D normal = Plane.Normal;
Vertex v0 = Plane.Origin;
double a = normal.X;
double b = normal.Y;
double c = normal.Z;
// 3 multiplications + 2 additions = maximum of 5*Machine_Eps
double d = -(a * v0.X + b * v0.Y + c * v0.Z);
// 3 multiplications + 3 additions = maximum of 6*Machine_Eps
Epsilon = 11 * Machine_Eps;
return a * v.X + b * v.Y + c * v.Z + d;
}
internal string DistanceSign(Vector3D v)
{
var distance = ComputeDistance(v);
return (distance > Epsilon ? "left" : (distance < -Epsilon ? "right" : "on"));
}
Ok now you can tell me how wrong I am. :)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DebtCalculator
{
class Program
{
static void Main(string[] args)
{
double creditcardbalance;
Console.WriteLine("Enter in credit card balance:");
creditcardbalance = double.Parse(Console.ReadLine());
double monthlypayementamount;
Console.WriteLine("Enter in the monthly payement amount:");
monthlypayementamount = double.Parse(Console.ReadLine());
double percentagerate;
Console.WriteLine("Enter in annual percentage rate:");
percentagerate = double.Parse(Console.ReadLine());
int payoff;
double dailyinterestrate;
dailyinterestrate = percentagerate / 365;
payoff = -(1 / 30) * Math.Log(1 + creditcardbalance / monthlypayementamount (1 - (1 + dailyinterestrate), Math.Pow(0, 30))) / Math.Log(1 + dailyinterestrate);
}
}
}
the "payoff = -(1 / 30) * Math.Log(1 + creditcardbalance / monthlypayementamount " where it says monthlypayementamount it returns an error of "method name expected" how do i resolve?
Looking at the formula your equation should be like this.
payoff = -(1d / 30) * Math.Log(1 + creditcardbalance / monthlypayementamount * (1 - Math.Pow(1 + dailyinterestrate, 30))) / Math.Log(1 + dailyinterestrate);
Your problems. in mathematics p(2) may translate to p*(2) but in coding you have to write everything p*(2).
And the part Math.Pow(0,30) evaluates to 0^30. you have to put 1 + dailyinterestrate (according to formula) instead of 0.
Also the result of this equation is type of double. but payoff as i see now is type of int. change the type of payoff to double or cast the result to int.
The other problem is -(1/30). they are both integer means the result is without decimal. so put d after the number so it will be type of double which holds decimal part. thanks to #A.S.H
You must Write the result in the console with Console.WriteLine() method
your code should look like this.
double payoff;
double dailyinterestrate;
dailyinterestrate = percentagerate / 365;
payoff = -(1d / 30) * Math.Log(1 + creditcardbalance / monthlypayementamount * (1 - Math.Pow(1 + dailyinterestrate, 30))) / Math.Log(1 + dailyinterestrate);
Console.WriteLine(payoff);