Roots of equation in C - c

I am relatively new to C, and am trying to improve myself in it. I made a calculator and added the quadratic equation solver to it, cause i know the formula of finding the roots. But i am faced with two problems.
Code:
#include <stdio.h>
#include <maths.h>
#include <stdlib.h>
#include <windows.h>
main(){
float A1, A2, A, B, C, ans, Z;
printf("Welcome to Quadratic Equation solver. Enter the coefficient of X^2, followed by\nthe coefficient of X, followed by the integer value.\n\nEnter values: ");
scanf("%f%f%f", &A, &B, &C);
CheckF = (B * B - 4 * A * C);
if (CheckF < 0) {
system("COLOR B4");
printf("This calculator HeX, currently cannot handle complex numbers.\nPlease pardon my developer. I will now redirect you to the main menu.\n");
system("pause");
system("cls");
system("COLOR F1");
goto Start;
} else if (CheckF >= 0) {
Z = pow(CheckF, 1/2);
A1 = (-B + Z)/(A+A);
A2 = (-B - Z)/(A+A);
if (A1 == A2) {
ans = A1;
printf("\nRoot of equation is %f (Repeated root)\n", ans);
Sleep(250);
} else if (A1 != A2) {
printf("Roots of equation are %f and %f \n", A1, A2);
Sleep(250);
}
}
}
Problem 1:
When i run the code and input 3 32 2, mathematically the output should be Roots of equation are -0.06287 and -10.6038, that i double checked with my sharp calculator. However, the output that i got was was off: Roots of equation are -5.166667 and -5.500000 i am totally unsure why is it not computing the correct roots of the equation.
Problem 2:
Some roots do not have the coefficient of X^2, for example (2X + 2), which can be solved to get repeated roots of -2, (6X - 3), which gives us that x is 0.5 repeated. However, according to the quadratic equation, which is divided by 2A, will never work, as it is divided by 0. What is the possible way out of this situation? Is it to check if A = 0 then do something else? Any help will be appreciable.

integer division
pow(CheckF, 1/2) is 1.0 as 1/2 is integer division with a quotient of 0.
// Z = pow(CheckF, 1/2);
Z = pow(CheckF, 1.0/2.0);
// or better
Z = sqrt(CheckF);
// Even better when working with `float`.
// Use `float sqrtf(float)` instead of `double sqrt(double)`.
Z = sqrtf(CheckF);
Best - re-write using double instead of float. Scant reason for using float here. double is the C goto floating point type.
Other issue
//#include <maths.h>
#include <math.h>
// main() {
int main(void) {
// CheckF = (B * B - 4 * A * C);
float CheckF = (B * B - 4 * A * C);
// goto Start;
Use an auto formater

I see some problems with the code. First, I suggest you to use double instead of float. They offer much better precision and an ideal calculator needs precision. Secondly, you do:
Z = pow(CheckF, 1/2);
You should use sqrt(CheckF) since there is a dedicated function in C for square roots! The following works for me so if you fix the above two problems, your code will probably work.
int main() {
double A1, A2, A, B, C, ans, Z;
printf("Welcome to Quadratic Equation solver. Enter the coefficient of X^2, followed by\nthe coefficient of X, followed by the integer value.\n\nEnter values: ");
A = 3;
B = 32;
C = 2;
double CheckF = (B * B - 4 * A * C);
if (CheckF >= 0) {
Z = sqrt(CheckF);
A1 = (-B + Z) / (A + A);
A2 = (-B - Z) / (A + A);
if (A1 == A2) {
ans = A1;
printf("\nRoot of equation is %f (Repeated root)\n", ans);
} else if (A1 != A2) {
printf("Roots of equation are %f and %f \n", A1, A2);
}
}
}

Related

Validating a triangle in C

I'm new in C, so I try to create a program that calculate the area of triangle as a start.
Calculating the area is easy when the triangle exists, however the validation of straight line is working partially.
Example:
A(0,-4) B(1,0) C(4,12) does not produce straight line error.
but
A(4,12) B(1,0) C(0,-4) produce straight line error.
#include <stdio.h>
#include <math.h>
double square(double num){
return (num*num);
}
int main()
{
double x[5],y[5],a,b,c,angle,area;
printf("Hello there! Calculating the area of triangle.\n");
printf("Enter a coordinate A :\n");
scanf("%lf,%lf",&x[0],&y[0]);
printf("Enter another coordinate B :\n");
scanf("%lf,%lf",&x[1],&y[1]);
printf("Enter another coordinate C :\n");
scanf("%lf,%lf",&x[2],&y[2]);
// AB as base (a) , c is opposite side
a = sqrt( square((x[0]-x[1])) + square((y[0]-y[1])) );
b = sqrt( square((x[0]-x[2])) + square((y[0]-y[2])) );
c = sqrt( square(x[1]-x[2]) + square((y[1]-y[2])) );
double num = (square(a)+square(b)-square(c))/(2*a*b);
angle = acos(num);
area = .5*a*b*sin(angle);
//printf("%lf %lf %lf %lf %lf \n",a,b,c,num,angle);
if (num == 1 || num ==-1){
printf("That's a straight line.");
}else{
printf("Area of triangle is %lf\n",area);
}
return 0;
}
You can use a different test, and perhaps a different area formula. If you use Heron's formula, then once you have the lengths of the sides a, b, and c, you can compute:
double p = (a + b + c)/2;
double area = sqrt(p*(p-a)*(p-b)*(p-c));
You can detect if the triangle is valid by checking that p is greater than each of the sides.
double p = (a + b + c)/2;
if ((p > a) && (p > b) && (p > c)) {
double area = sqrt(p*(p-a)*(p-b)*(p-c));
printf("Area of triangle is %lf\n", area);
} else {
printf("I don't consider that a triangle.\n");
}
Try it online!
The problem in your code is double num = (square(a)+square(b)-square(c))/(2*a*b); gets evaluated to a number slightly larger than 1 in some cases. This can happen with floating point computations. In your case you can safely add if (num > 1) num = 1; after that line since cosine equation always will give you a value larger than 0 and less than 1 for triangles.
However there's a problem if two points overlap and a or b becomes zero. You will have to check for that and handle it as a special case if such input is expected by your code. (If two points overlap then they are collinear anyways. You can check the overlap by checking if any of a,b,c are zero)

Rotation program in C

I'm basically trying to make a math rotation program in C. But the output is always wrong. P(x,y) is rotated about Q(r,s); clockwise (direction=1) or anticlockwise (direction=0). The a,b,c are angles in triple ,I guess question meant c is in hundred's then b is in ten's and a is unit's.
Input:
0
7 3
0 1 1
0 0
Output: -3 7
Whereas I'm getting -5 5.
Thanks for your time if you help me.
Original question link: https://www.codechef.com/problems/DSPC305
i found another question by the same uploader which uses TRIPLE too. He further added a note :Triple is defined by a,b,c where a is base, b is height and c is hypotenuse of a triangle. Each triple corresponds to an angle given by cosA= a/c
#include<stdio.h>
#include<math.h>
int main() {
int x,y,a,b,direction,c,r,s,xnew,ynew;
scanf("%i", &direction);
scanf("%i %i", &x, &y);
scanf("%i %i %i" , &a, &b, &c);
scanf("%i %i", &r, &s);
float PI = 3.1415926535897932384626;
float theta = ((c*100+b*10+a)*PI)/180;
if (direction==1)
{
xnew= (x-r) * cos(theta) + (y-s) * sin(theta);
ynew= -(x-r) * sin(theta) + (y-s) * cos(theta);
printf("%i %i", xnew+r, ynew+s);
}
if (direction==0)
{
xnew =( (x-r) * ((cos(theta))) - (y-s) * sin(theta));
ynew =( (x-r) * ((sin(theta))) + (y-s) * cos(theta));
printf("%i %i", (xnew+r), (ynew+s));
}
return 0;
}
This
float theta = ((c*100+b*10+a)*PI)/180;
has nothing to do with the definition of a triple.
You can use this code:
#include<stdio.h>
#include<math.h>
int main()
{
double xp,yp,xq,yq,a,b,c;
double t,xn,yn;
int z;
scanf("%d",&z);
scanf("%lf%lf",&xp,&yp);
scanf("%lf%lf%lf",&a,&b,&c);
scanf("%lf%lf",&xq,&yq);
t=asin(b/c);
if(z==0)
{
xn=xp*cos(t)-yp*sin(t)-xq*cos(t)+yq*sin(t)+xq;
yn=xp*sin(t)+yp*cos(t)-xq*sin(t)-yq*cos(t)+yq;
}
else
{
xn=xp*cos(t)+yp*sin(t)-xq*cos(t)-yq*sin(t)+xq;
yn=-xp*sin(t)+yp*cos(t)+xq*sin(t)-yq*cos(t)+yq;
}
printf("%0.lf %0.lf",xn,yn);
return 0;
}
This code gave correct output for both of the test cases provided in the question.
Do tell if it worked :)

Trapezoidal Riemann Sum in C

I've been trying to do Riemann Sums to approximate integrals in C. In my code below, I'm trying to approximate by both the trapezoidal way and the rectangular way (The trapezoidal way should be better, obviously).
I tried making an algorithm for this on paper, and I got the following:
NOTE: N is the number of rectangles (or trapezoids) and dx is calculated using a, b and N ( dx = (b-a)/N ). f(x) = x^2
Rectangular Method:
<img src="http://latex.codecogs.com/png.latex?\int_a^b&space;x^2&space;dx&space;\approx&space;\sum_{i=1}^N&space;f(a&space;&plus;&space;(i-1)dx)dx" title="\int_a^b x^2 dx \approx \sum_{i=1}^N f(a + (i-1)dx)dx" />
Trapezoidal Method:
<img src="http://latex.codecogs.com/png.latex?\int_a^b&space;x^2&space;dx&space;\approx&space;\sum_{i=1}^N&space;[f(a&space;&plus;&space;(i-1)dx)&space;&plus;&space;f(a&space;&plus;&space;i\cdot&space;dx)]dx" title="\int_a^b x^2 dx \approx \sum_{i=1}^N [f(a + (i-1)dx) + f(a + i\cdot dx)]dx" />
Code (In the following code, f(x)=x^2 and F(x) is it's antiderivative (x^3/3):
int main() {
int no_of_rects;
double a, b;
printf("Number of subdivisions = ");
scanf("%d", &no_of_rects);
printf("a = ");
scanf("%lf", &a);
printf("b = ");
scanf("%lf", &b);
double dx = (b-a)/no_of_rects;
double rectangular_riemann_sum = 0;
int i;
for (i=1;i<=no_of_rects;i++) {
rectangular_riemann_sum += (f(a + (i-1)*dx)*dx);
}
double trapezoidal_riemann_sum = 0;
int j;
for (j=1;j<=no_of_rects;j++) {
trapezoidal_riemann_sum += (1/2)*(dx)*(f(a + (j-1)*dx) + f(a + j*dx));
printf("trapezoidal_riemann_sum: %lf\n", trapezoidal_riemann_sum);
}
double exact_integral = F(b) - F(a);
double rect_error = exact_integral - rectangular_riemann_sum;
double trap_error = exact_integral - trapezoidal_riemann_sum;
printf("\n\nExact Integral: %lf", exact_integral);
printf("\nRectangular Riemann Sum: %lf", rectangular_riemann_sum);
printf("\nTrapezoidal Riemann Sum: %lf", trapezoidal_riemann_sum);
printf("\n\nRectangular Error: %lf", rect_error);
printf("\nTrapezoidal Error: %lf\n", trap_error);
return 0;
}
Where:
double f(double x) {
return x*x;
}
double F(double x) {
return x*x*x/3;
}
I have included the math and stdio header files. What is happening is that the rectangular riemann sum is okay, but the trapezoidal riemann sum is always 0 for some reason.
What is the problem? Is it something in my formulas? Or my code?
(I am a newbie in C by the way)
Thanks in advance.
In this statement:
trapezoidal_riemann_sum += (1/2)*(dx)*(f(a + (j-1)*dx) + f(a + j*dx));
1/2 == zero, so the whole statement is zero. Change at least the numerator, or the denominator to the form of a double to get a double value back. i.e. 1/2.0 or 1.0/2 or 1.0/2.0 will all work.

how to put in mathematical equation in C

I've been trying to look up on Google how to put in an equation in my program but wasn't able to find any. How do you include:
x = ( -b + √b2 - 4ac ) / 2a
in the program?
Here's my code:
{
int a, b, c;
float x;
//statements
printf("Enter three integers: ");
scanf("%d %d %d", &a, &b, &c);
//computeforX
x = ( -b + √b2 - 4ac ) / 2a
printf("The value of x is %.1f", x);
return 0;
}
Assuming we're talking about C (or C++) here, you will need to investigate the sqrt function, and maybe also the pow function as well (although that's unnecessary because b-squared can be computed as b*b).
Note that you will need to convert all of your input values to float or double before you start the calculation, otherwise you will not get the intended result.
You need a table to allow you to translate:
a+b -> a+b
a-b -> a-b
a/b -> a/b
ab -> a*b
√x -> sqrt(x)
x² -> x*x (If you want to square something more complicated it might be best to use a temporary variable for the value to be squared, breaking your equation up into pieces.)
Note that if you divide an int by an int in C you get an int. So better convert those ints to doubles before dividing.
If we are dealing with C++ it would be something like
#include <iostream.h>
#include <cmath>
int main ()
{
//Declare Variables
double x,x1,x2,a,b,c;
cout << "Input values of a, b, and c." ;
cin >>a >>b >>c;
if ((b * b - 4 * a * c) > 0)
cout << "x1 = (-b + sqrt(b * b - 4 * a * c)) / (2 * a)" &&
cout << "x2 = (-b + sqrt(b * b - 4 * a * c)) / (2 * a)";
if else ((b * b - 4 * a * c) = 0)
cout << "x = ((-b + sqrt(b * b - 4 * a * c)) / (2 * a)"
if else ((b * b - 4 * a * c) < 0)
cout << "x1 = ((-b + sqrt(b * b - 4 * a * c) * sqrt (-1)) / (2 * a) &&
cout << "x2 = ((-b + sqrt(b * b - 4 * a * c) * sqrt (-1)) / (2 * a);
return (0);
}
Now why do i have this wierd feeling I just did someone's first semester programming class' homework?
Granted its been years and I don't even know if that will compile but you should get the idea.
I am really depressed looking the quality of above answers and help, which has been given.
I hope to improve the content of this thread.
One can compile the C file below with the command line gcc file.c -o file -lm.
Herewith a possible solution in C:
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
int main(){
int da, db, dc;
double x, a,b,c;
//statements
printf("Enter three integers: ");
scanf("%d %d %d", &da, &db, &dc);
a = (double)da;
b = (double)db;
c = (double)dc;
//computeforX
x = (double) ( -b + sqrt(b * b) - 4 * a * c ) / ( 2 * a ) ;
printf("The value of x is %g \n", x);
return 0;
}

Problem finding the local maximum of a function in C

I'm designing an algorithm to define a simple method able to find the local maximum of a function f (x) given in an interval [a, b]
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define PI 3.141592653
float funtion_(float a, float x){
float result=0;
result = a * (sin (PI*x));
return result;
}
int main (){
double A = 4.875; //average of the digits of the identification card
double a = 0.0, b =1.0; //maximum and minimum values of the interval [a, b]
double h=0;
double N;
double Max, x;
double sin_;
double inf;
printf ("input the minux value: ");
scanf ("%lf", &inf);
printf ("input the N value: ");
scanf ("%lf", &N);
h= (b-a)/N;
printf("h = %lf\n", h);
x=a-h;
Max = -inf;
do {
x = x+h;
sin_ = funtion_(A, x);
if (sin_>=Max){
Max = sin_;
}
}while (x==b);
printf ("Maximum value: %lf.5", Max);
return 0;
}
The algorithm implements the function f (x) = A * sin (pi * x), where A is the average of the digits of my ID, and inf variable is assigned a number sufficiently greater than the values ​​reached by the function in the interval [a, b] = [0.1].
The algorithm must find the local maximum of the function but it is the maximum returns always zero. do not understand why. What problem may be the logic of my solution?, this problem can be solved by this simple algorithm or some optimization by backtracking is necessary ? Thanks for your responses.
Several problems with this code; probably the most glaring is:
int a = 0, b = 1;
float Max, x;
/* ... */
do {
/* ... */
} while (x == b);
You cannot compare an int and a float for equality. It might work once in a great while due to dumb luck :) but you cannot expect this code to function reliably.
I strongly recommend changing all your int variables to double, all your float variables to double, and all the scanf(3) and printf(3) calls to match. While you can combine different primitive number types in one program, and even in one expression or statement, subtle differences in execution will take you hours to discover.
Furthermore, comparing floating point formats for equality is almost never a good idea. Instead, compare the difference between two numbers to a epsilon value:
if (fabs(a-b) < 0.001)
/* consider them equal */
You might want to scale your epsilon so that it matches the scale of your problem; since float really only supports about seven digits of precision, this comparison wouldn't work well:
if (fabsf(123456789 - 123456789.1) < 0.5)
/* oops! fabsf(3) used to force float */
/* and float can't tell the difference */
You might want to find a good introduction to numerical analysis. (Incidentally, one of my favorite classes back in school. :)
update
The core of the problem is your while(x == b). I fixed that and a few smaller problems, and this code seems to work:
#include
#include
#include
#define PI 3.141592653
float funtion_(float a, float x)
{
float result = 0;
result = a * (sin(PI * x));
return result;
}
int main()
{
float A = 4.875; //average of the digits of the identification card
float a = 0.0, b = 1.0; //maximum and minimum values of the interval [a, b]
float h = 0;
float N;
float Max, x;
float sin_;
float inf;
printf("\ninput the inf value: ");
scanf("%f", &inf);
printf("\ninput the N value: ");
scanf("%f", &N);
h = (b - a) / N;
x = a - h;
Max = -inf;
do {
x = x + h;
sin_ = funtion_(A, x);
if (sin_ >= Max) {
Max = sin_;
printf("\n new Max: %f found at A: %f x: %f\n", Max, A, x);
}
} while (x < b);
printf("Maximum value: %.5f\n", Max);
return 0;
}
Running this program with some small inputs:
$ ./localmax
input the inf value: 1
input the N value: 10
new Max: 0.000000 found at A: 4.875000 x: 0.000000
new Max: 1.506458 found at A: 4.875000 x: 0.100000
new Max: 2.865453 found at A: 4.875000 x: 0.200000
new Max: 3.943958 found at A: 4.875000 x: 0.300000
new Max: 4.636401 found at A: 4.875000 x: 0.400000
new Max: 4.875000 found at A: 4.875000 x: 0.500000
Maximum value: 4.87500
$
You are doing your calculations, in particular the initialisation of h, with integer arithmetic. So in the statement:
h = (b-a) / N;
a, b, and N are all integers so the expression is evaluated as an integer expression, and then converted to a float for assignment to h. You will probably find that the value of h is zero. Try adding the following line after the calculation of h:
printf("h = %f\n", h);
After you've fixed that by doing the calculations with floating point, you need to fix your while loop. The condition x = b is definitely not what you want (I noticed it was originally x == b before your formatting edit, but that's not right either).
Should the while condition be: while(x <= b)
while (x = b);
There is no way to exit the loop. b is always 1.

Resources