I am writing a program in C that calculates this formula:
(source: crewtonramoneshouseofmath.com)
here is the line of code (I am just using + instead of the +-):
x = ((-1 * b) + (sqrt(pow(b, 2) - 4 * a * c)))/(4 * a);
I am not getting the correct root. For example if a = 1, b=-2, and c=-2 it SHOULD be 2.73. Instead I am getting 1.37.
Been staring at the code and I don't see the mistake. Can someone point it out for me?
x = (...) / (4 * a)
Shouldn't this be 2 * a?
It's interesting that 1.37 (what you're getting) is about half of 2.73 (what you want) and, lo and behold, there it is in your denominator, dividing by 4a instead of 2a.
Personally, I would write that expression as:
x = (-b + sqrt (b * b - 4 * a * c)) / (2 * a);
since it more closely matches the equation you're trying to duplicate (the -1 * b is better expressed as -b) and I find calling pow to get a simple square to be unnecessary where b * b does the same job without a function call.
x1 = ((-1 * bcoeff) + (sqrt(pow(bcoeff, 2) - 4 * acoeff * ccoeff)))/(2 * acoeff);
Check yourself here: .../(4 * acoeff)
While this question has already been answered and your error pointed out. I would just like to mention that breaking the problem down into more lines would increase its readability and potentially reduce mistakes made.
float den = 2 * a;
float num1 = (-1 * b);
float num2 = pow(b ,2) - (4 * a * c);
float x = (num1 + sqrt(num2))/ den;
Related
I was looking in my C textbook and inside there was a page where the prompt told me to translate a polynomial into C code. We have not discussed exponent operators yet and are specifically instructed not to use them at this point and find another way with basic operators. The polynomial goes as such: 5x^(2)+3x-2.
How do I do this?
Note that ax^2 + bx + c can be written as
c + x*(b + x*(a))
This can easily be extended to any order of polynomial.
There is no such thing as an exponent operator in C. While you can accomplish the same thing using pow(). I suspect your book does not want this. Given this limitation you can do the operation of x^2 as simply x * x where x is a variable for your function.
i.e. You can do something like this:
int poly(int x) {
int y = ((5 * x * x) + (3 * x) - 2);
return y;
}
Addendum:
If you want to have a general formula that you can easily extend for any polynomial degree, you can use this formula instead, with inputs for a, b, c and x:
int poly(int a, int b, int c, int x) {
int y = c + x*(b + x*(a));
return y;
}
Thanks to chux and FredK for this.
I think you should parameter a,b,c and x in the second polynomial function
int poly2(int a, int b, int c, int x)
{
int y = a*x*x+b*x+c;
return y;
}
when using this function for your case you can call
int result = poly2(a,b,c, x)
with a specific set of a,b,c,x
C doesn't have an exponent operator.
One really handy way to model polynomials is to use an array to store the coefficients, such that the array index corresponds to the power of x. IOW, to model 5x2 + 3x - 2, use
double coef[] = {-2.0, 3.0, 5.0}; // -2.0 + 3.0x + 5.0x^2
To evaluate the polynomial, use a loop, taking into account the property that FredK mentions in his answer - 5x2 + 3x - 2 == ((5)x + 3)x - 2:
size_t num_elements = sizeof coef / sizeof coef[0]; // yields 3 in this case
double result = 0;
for (size_t i = num_elements - 1; i > 0; i--)
result += x * ( result + coef[i] );
result += coef[0];
This method will work for polynomials of any degree.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
double a;
double b;
double q0 = 0.5 * M_PI + 0.5 * -2.1500000405000002;
double q1 = 0.5 * M_PI + 0.5 * 0.0000000000000000;
double w0 = 0.5 * M_PI + 0.5 * -43000.0008100000050000;
double w1 = 0.5 * M_PI + 0.5 * -0.0000000000000000;
double m = 1;
double g = 43000000.81;
double l1 = 0.1;
double l2 = 0.1;
double h = 0.0001;
a = ((-g / l1) * sin(q0) + (sin(q1 - q0) * (cos(q1 - q0) * (w0 * w0 + (g / l1) * cos(q0)) + l2 * (w1 * w1 / l1))) / (m + pow(sin(q1 - q0), 2)));
a = h * a;
b = h * ((-g / l1) * sin(q0) + (sin(q1 - q0) * (cos(q1 - q0) * (w0 * w0 + (g / l1) * cos(q0)) + l2 * (w1 * w1 / l1))) / (m + pow(sin(q1 - q0), 2)));
printf("%.20lf ", a);
printf("%.20lf", b);
return 0;
}
I do the same calculations with a and b, just with the difference that I get the value of a in two steps, and the b in one.
My code returns:
-629.47620126173774000000 -629.47620126173763000000
What is the reason of the difference between the two last decimals?
The C Standard (99 and 11) says:
The values of operations with floating operands and values subject to the usual arithmetic conversions and of floating constants are evaluated to a format whose range and precision may be greater than required by the type.
So in an expression such as h*(X+Y) as you have in the assignment to b, the implementation is allowed to use greater precision for the intermediate result of X+Y than can possibly be stored in a double, even though the type of the subexpression is still considered to be double. But in a=X+Y; a=h*a;, the first assignment forces the value to be one that actually can be stored in a double, causing a slightly different result.
Another possibility is that the compiler has done "floating point contraction". To quote the C Standard again,
A floating expression may be contracted, that is, evaluated as though it were an atomic operation, thereby omitting rounding errors implied by the source code and the expression evaluation method.
This would most likely happen if the processor has a single instruction that can do a floating point addition and then a multiplication in one step, and the compiler decided to use it.
Assuming one or both of these is the cause, your value b is likely a more accurate representation of the computation you specified (given that all the inputs were restricted to values which can be represented in a double).
The cppreference page about macro FLT_EVAL_METHOD discusses both of these issues in a little more detail. It may be interesting to find out your value of FLT_EVAL_METHOD and play with #pragma STDC FP_CONTRACT OFF.
The answer is because in the float numbers calculations the equation a=bcde does not have to be equal to x = bc y = de and a.= xy.
It is because floating point arithmetic has a limited precision.
I'm working on writing a C program to perform division of 2 complex numbers in Fixed Point.
I'm not able to get the fractional part from it. Below is more details on it.
I have 2 complex numbers:
N = a + ib
M = c + jd
I need to do N/M in fixed point (not using floating point)
Example values for the above complex numbers can be:
a = 1.55, b = 1.44, c = 1.24, d = 0.55
N = 1.55 + i(1.44)
M = 1.24 + j(0.55)
For converting to Fixed Point, I multiply these a, b, c and d with 2^14.
After that they become:
a = 0x6333, b = 0x5c28, c = 0x4f5c and d = 0x2333
Then to perform the N/M operation I do:
N/M = (a + ib)/(c + jd) = ((a + ib) * (c - jd)) / ((c + jd) * (c - jd))
Then for the real part alone:
(ac + bd) / (c^2 + d^2)
and so on..
The issue I'm facing is that I'm not understanding how to get the fractional part from the division.
I'm getting only the decimal part which is mostly either 1 or 0.
What is the correct way to get the fractional part? In the above example, the real part should be something like 1.47490. But I'm only able to get 1.
Can anyone please help me with the right way in doing the complex division for Fixed Point?
Thank you very much.
In fixed point division and multiplication one must notice that the result value must have also scaling factor K.
in addition / subtraction:
a * K + b * K = K * ( a + b)
in multiplication:
(a * K) * (b * K) = K^2 * (a * b) --> must compensate with 1/K
proper form: (aK * bK) / K
in division:
(a * K) / (b * K) = a / b --> must pre-multiply with K
proper form: (aK * K) / (bK)
For two complex X=a+jb, and Y=c+jd, where j=sqrt(-1), and a, b, c, d are real numbers, the division X/Y is given by
(ac+bd)/(c^2+d^2) + j(bc-ad)/(c^2+d^2)
Let K = 2^14, the binary digit for saving the fraction, as you mentioned.
Let A is the fixed number representation of a, i.e. A = a * K, and similarly let B = b*K, C=c*K, and lastly D=d*K. Assume your number is not big enough to overflow the integer of your computer, in the following calculations:
You should first calculate U = A * C + B * D, V = C * C + D * D, W = B * C - A * D
Then, you should calculate V' = V >> 14. Then, the real part of X/Y is U/V', and the imaginary part of X/Y is W/V', with both parts represented in your fixed point form.
I need to find out the value of nPr%m.
This is the approach I used.
Find, n!%m, (n-r)!%m and divide them
However, for certain cases, (n-r)!%m is greater than n!%m, so the resultant nPr is 0.
What do I need to do then?
This is more a math question than a programming question, but anyway.
Note that
n! / (n - r)! = n * (n - 1) * ... * (n - r + 1)
Now for multiplication,
(a * b * c) % m = (((a * b) % m) * c) % m
i.e. rather than mod ming the entire product, you can mod m the intermediate result of any multiplication of two factors in the product.
I won't provide the full code here, but hopefully this will be enough for you to figure it out.
I have the following in a program (part of a much larger function, but this is the relevant testing bit):
int test = 100 + (100 * (9 / 100));
sprintf (buf, "Test: %d\n\r", test);
display_to_pc (buf, player);
Basically it amounts to:
x = a + (a * (b / 100))
Where a is a given figure, b is a percentage modifier, and x is the result (the original plus a percentage of the original)... I hope that makes sense.
It gives me:
Test: 100
I thought the math in my head might be wrong, but I've checked several calculators and even the expression evaluator in my IDE, and they all give me the expected result of 109 for the first expression.
Can anyone enlighten me as to what I'm missing here?
Thanks much. :)
Replace
int test = 100 + (100 * (9 / 100));
with
int test = 100 + (100 * 9 / 100);
// x = a + (a * b / 100)
and it will work as expected. 9 / 100 is performed using integer division; the nearest integer to .09 is 0 (and 0 * 100 is still 0).
Doing the multiplication first results in 900 / 100, which gives you the 9 that you were expecting.
If you need more than integer precision, you may need to go the floating point route.
You're using integer math.
9/100 = 0.
100 + (100 * (0) = 100.
Your calculators use floating point math, and can handle decimals appropriately.
As others have pointed out, the problem is that you are doing integer arithmethic. You need to do the calculation as floating point by casting the variable to double or using a double constant, then allow truncation to give you just the integer portion.
x = a + (a * (b / 100.0));
or
x = a + (a * ((double)b / 100)));
Your mistake is that 9 / 100 is interpreted as integer division, and evaluates to 0 and not 0.09.
You can write 9 / 100.0 instead, or rearrange the expression.
int test = 100 + (100 * (9 / 100));
9/100 = 0
0 * 100 = 0
100 + 0 = 100
you are using integer division so 9 / 100 is zero so test = 100 + 0 = 100
Use Daniel L's answer if you will only be working with expressions that will result in whole integer values. If the values you'll be working with are less clean, use double literals instead of integer literals:
int test = 100.0 + (100.0 * (9.0 / 100.0));
The answer of 9/10 gets truncated to 0, and then you multiply that by 100, and then add 100 to it.
Change:
int test = 100 + (100 * (9 / 100));
to
int test = (int)(100 + (100 * (9 / 100.0)));
and see if it works as expected.
EDIT: wow. Lots of answers while I was typing. Most of them will work, too.
You should be using floating point arithmetic so 9/100 becomes 0.09.
int test = 100.0 + (100.0 * 9.0 / 100.0);
You are using integers for your variable types, so the inner most expression (9 / 100) will result in a 0. Then the next expression would be 100 * 0, which is 0, and finally 100 + 0...
To get your desired result try using float instead:
float test = 100.0 + (100.0 * (9.0 / 100.0));
printf("result: %0.2f\n", test);