How to convert a math equation (summation) to a code? [closed] - c

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
Using two functions:
Factorial Function
Power Function
Develop a C program for the following equation:
I've done this . but no output.
#include <stdio.h>
#include <math.h>
double factorial(double x);
double Power_function(double y);
int main(){
double answer=0;
double n;
double y;
printf("Enter Y :The last limit of the summation:>");
scanf("%ld",&y);
for (n=1;n<=y;++n){
answer=answer +factorial(n)*Power_function(n)*y;
}
printf("The Answer is %0.2f\n",answer);
return 0;
}
double factorial(double x)
{
double ans;
if (x==0){
ans = 1;
}
else
{
ans = x*factorial(x-1);
}
return ans;
}
double Power_function(double y){
double ans;
ans=pow(2,y);
return ans;
}

I've a suspicion what one of the learning outcomes of this is and too much help here will give the game away.
I think i can safely say you need to break each part of the equation down to smaller solvable parts.
The three biggest parts are summation, N Factorial (N!) and 2 to the power N
The summation is effectively a loop with N starting at 1 and ending at y, so look for the C syntax to write a loop (hint there are two common types, while and for)
The other two are functions, if your allowed to use premade functions then plenty exist only a google away which will sort you out nicely, if not you'll have to write your own.
factorial is n*(n-1)*(n-2)...(n-(n-2))*(n-(n-1))
so 4! = 4*3*2*1
a prime candidate for a recursive function or a function with a descending loop in it
2 to the power n is 2 multiplied by itself n times
so 2 to the power 2 = 2*2
2 to the power 3 = 2*2*2 and so on
Once again a loop looks like a good place to start with that.
After that its just a matter of using your two functions inside the loop, giving the user a way to input Y and testing with some numbers.
1,2,3 would be a good start as they're nice and easy to work out on a calculator.
All well and good so far I'd hope, -1 should make interesting things happen to every example I've seen posted so far, and that's before we start pushing the boat out with big numbers like 32.
Edit:
Right, I've taken a look at your code, and it looks like your problem isn't in the implementation of your algorithm, its not reading the variable in correctly, outputing y just after you set it yields 0, so something isn't working quite right there. Im not a c coder but i had a quick hack at it with some liberal googling and your non functional code and made it read an argument in then parse it to a double.
#include<stdio.h>
#include<math.h>
double factorial(double x);
double Power_function(double y);
main(int argc, char *argv[]){
double answer=0;
double n;
double y;
y = atol(argv[1]);
//printf("%lf\n",y);
for (n=1;n<=y;++n){
answer=answer +factorial(n)*Power_function(n)*y;
}
printf("The Answer is %0.2f\n",answer);
return 0;
}
double factorial(double x)
{
double ans;
if (x==0){
ans = 1;
}
else
{
ans = x*factorial(x-1);
}
return ans;
}
double Power_function(double y){
double ans;
ans=pow(2,y);
return ans;
}
So essentially your code with a different input method,
compiled using
gcc so.c -lm
executed as
./a.out 1
yields The Answer is 2.00
./a.out 2
yields The Answer is 20.00
./a.out 3
yields The Answer is 174.00
Pen and paper maths backs it up so your algorithm is sound so far!
Feed it some negative numbers and some huge numbers to see what it does from here!

I didn't do everything for you, but here is a basic outline.
You must finish it off.
int answer = 0;
int n;
for(n=1; n <= y; ++n)
{
answer = answer + (n! * 2^n)*y;
}

You're looking for the sum of (n! * 2^n) from 1 to y.
total variable is 0
for 1 until y:
multiply factorial(n) and pow(2, n) and add this to total
end of loop
print out total

First thing to do is to write down what you manually would do to work that equation out. Try out 1 to 5, for example, and see what you get.

Related

Calculate cosine in C

We are doing C Programming in school and we have to calculate the cosine of a number with use of the "Taylor series" (https://en.wikipedia.org/wiki/Taylor_series). I know C programming but that what we have to do has not really much to do with programming itself more than being good in math.
If you put in your calculator cos(50) it's 0.6427.... That's what we have to do in C. There is the cos() function in math.h but that's not actually the cosine. I am overwhelmed with this and don't really know what we have to do. It should look something like this:
#include <stdio.h>
#include <conio.h>
#include <math.h>
int fac(int n);
double meincosinus(double x);
void main() {
double x;
double y;
int i;
printf("geben sie eine zahl ein\n");
scanf_s("%lf", &x);
y = meincosinus(x);
printf_s("cos(%lf)=%lf\n", x, y);
y = sin(x);
printf_s("cos(%lf)=%lf\n", x, y);
scanf_s("%d", &i);
printf_s("%d\n", i);
_getch();
}
int fac(int n) {
int prod = 1;
int i;
for (i = 1; i <= n; i++)
{
prod *= i;
}
return prod;
}
double meincosinus(double x)
{
double erg = 0;
int n;
for (n = 0; n <= x; n++)
{
x = fac(n);
erg += pow(-1, n) * pow(x, (2 * n)) / fac(2 * n);
}
return erg;
}
This code runs but the output is wrong.
Not an answer (but, well, I am a teacher myself, I am not gonna make your homework :)). But a few questions you should ask yourself and that might help you
Why are you comparing your Taylor computation of cosinus with the "real" sinus? Shouldn't y=sin(x) be y=cos(x), for a pertinent comparison?
why are you doing this: x = fac(n);? You are overwriting your x argument to "meinconsinus". You can't expect meincosinus(50) to really compute cos(50) if the first thing you do is overwriting that "50" with something else (namely n!).
also, why this for (n = 0; n <= x; n++). You know the Taylor formula better that I do (since you are studying it right now). It sure not supposed to stop after x iterations. x is rarely even an integer. It is supposed to be very small anyway. And could even be negative. So, question you've to ask yourself is, how many iterations (up to which term of the series) you want to compute. It is a rather arbitrary choice, since from Taylor point of view, answer is ∞. But on a computer, after a while it is no use to add extremely small numbers
Since I am mentioning the fact that x is supposed to be small: you can't compute cos(50) that way with a Taylor formula. You could compute cos(0.1) or even cos(1) maybe, with enough iterations. But 50 is not a small enough number. Plus, 50ⁿ will be very quickly out of control in your loop. If you really want meincosinus to be able to handle any number, you have first to reduce x, using trigonometric rules: cos(x)=cos(x)-2π; cos(x)=-cos(x); cos(x)=sin(π/2-x); ... There are some better rules, but with those simple ones, you can have x in [0,π/4]. Since π/4<1, at least you don't have an explosive xⁿ.
Also, but that is an optimization, you don't really need to compute neither (-1)ⁿ with pow (just alternate a int sign variable, between -1 and 1 at each iteration), nor x²ⁿ (just multiply a double x2n=1 by x*x each iteration), nor fac(2n) (just multiply a f=1 variable by (n-1)×n, being careful with 0 case, at each iteration.

Why does my approximation of Exponential using Taylor Series expansion return "inf"?

This is my homework:
I haven't tried to write the part of Natural Logarithm because I can't solve the part of Exponential.
This is the the approximations of Exponential in C using Taylor Series expansion I wrote.
However, it returns inf. What did I do wrong?
#include <stdio.h>
// Returns approximate value of e^x
// using sum of first n terms of Taylor Series
float exponential(int n, float x)
{
float sum = 1.0f; // initialize sum of series
for (int a = n; a >= 0; ++a ) {
while (x * sum / a < 0.00001) {
break;
}
sum = 1 + x * sum / a;
return sum;
}
}
int main()
{
int n = 0;
float x = 1.0f;
printf("e^x = %.5f", exponential(n, x));
return 0;
}
With How do I ask and answer homework questions? in mind, I will give you a few things to have a careful look at.
From comment by Spektre:
from a quick look you are dividing by zero in while (x * sum / a < 0.00001) during first iteration of for loop as a=n and you called the function with n=0 ... also your code does not match the expansion for e^x at all
Have a look at the for loop:
for (int a = n; a >= 0; ++a )
What is the first value of a? The second? The third?
Keep in mind that the values are determined by ++a.
When will that loop end? It is determined by a >= 0. When is that false?
What is this loop doing?
while (x * sum / a < 0.00001) {
break;
}
I suspect that you programmed "English to C", as "do the outer loop while ...", which is practically from the assignment.
But the loop does something else. Apart from risking the division by 0 mentioned above, if the condition is true it will stay true and cause an endless loop, which then however is immediatly canceled in the first iteration.
The head of your function float exponential(int n, float x) expects n as a parameter. In main you init it with 0. I suspect you are unclear about where that value n is supposed to come from. In fact it is unknown. It is more a result of the calculation than an input.
You are supposed to add up until something happens.
You do not actually ever need the value of n. This means that your for loop is meaningless. The inner loop (though currently pointless) is much closer to your goal.
I will leave it at this for now. Try to use this input.
Feel free to edit the code in your question with improvements.
(Normally that is not appreciated, but in case of homework dialog questions I am fine with it.)
Your current implementation attempt is quite a bit off. Therefore I will describe how you should approach calculating such a series as given in your quesiton.
Let's look at your first formula:
You need to sum up terms e(n) = x^n / n!
To check with your series: 1 == x^0 / 0! - x == x^1 / 1! - ...
To calculate these terms, you need a simple rule how to get from e(n) to e(n+1). Looking at the formula above we see that you can use this rule:
e(n+1) = e(n) * x / (n+1)
Then you need to create a loop around that and sum up all the bits & pieces.
You are clearly not supposed to calculate x^n/n! from scratch in each iteration.
Your condition to stop the loop is when you reach the limit of 1e-5. The limit is for the new e(n+1), not for the sum.
For the other formulas you can use the same approach to find a rule how to calculate the single terms.
You might need to multiply the value by -1 in each step or do something like *x*n/(n+1) instead of *x/(n+1) etc.
Maybe you need to add some check if the formula is supposed to converge. Then maybe print some error message. This part is not clear in your question.
As this is homework, I only point into the direction and leave the implementation work to you.
If you have problems with implementation, I suggest to create a new question.
#include <stdio.h>
int main() {
float power;
printf("Enter the power of e\n");
scanf("%f", &power);
float ans = 1;
float temp = 1;
int i = 1;
while ((temp * power) / i >= 0.00001) {
temp = (temp * power) / i;
ans = ans + temp;
i++;
}
printf("%.5f", ans);
return 0;
}
I think I solved the problem
But the part about Natural Log is not solved, I will try.

How to stop rounding decimals with double in c

I know this problem has been on the internet for a while but i cant seem to find how to stop my program from rounding the 3rd decimal.
the answer output is 4524.370 and should be 4524.369
also, i know my equations are stupid and could be simplified but im lazy
//Tanner Oelke CSE155E
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int main(void){
double v, t; //base variables
double sq1, sq2; //calculation variable for square root
printf("Please enter the given air temperature in Fahrenheit:");
scanf("%lf", &t);
//unessecary equations but it works
sq1=(57*t+297);
sq2=(sq1/247);
v=1086*sqrt(sq2);
printf("%.3lf\n", v);
return 0;
}
With an input of "70.0" the result is 4524.369754... which displays as "4524.370" - What OP gets.
With an input of "69.999975" the result is 4524.369002... which displays as "4524.369" - what OP wants.
If OP expects "70.0" to result in "4524.369", then some minor adjustment to the formula is needed. The precision of double is at least 10 significant digits and often is 15+. Even doing this in float then f(70.0)--> 4524.370.
Else OP has the wrong expectation.
Response to OP's comment:
"to shorten the decimal place to 3 spots without rounding". Hmmm seems strange to want this:
// properly rounded result
printf("%.3lf\n", v);
// shorten to 3 places without rounding
double v3 = floor(v*1000.0)/1000.0;
printf("%.3lf\n", v3);

How to calculate the differential coefficient in c

Thanks a lot people for your help so far but I made a big mistake I need the derivation of a function at a specific point!
I have to calculate the first derivation of a function and I really have no clue how to get there. If I just had to calculate it for a function with just a X^1 I would know how to but I'm really stuck here.
Old Stuff:
A function can look like 2*x^2+1.
The method has to look like this: double ab(double (f)(double),double x)
and my professor gave us the hint that we might should use the function:
(f(x0+∆x)−f(x0))/((x0+∆x)−x0).
Sorry for my bad English and thanks for any kind of hint or tip in advance.
this sample will get you started :
#include<stdio.h>
#include <stdlib.h>
float func(float x)
{
return(2*x*x + 1);
}
int main(){
float h=0.01;
float x;
float deriv, second;
printf("Enter x value: ");
scanf("%f", &x);
// derivative at x is the slope of infinitely small
// line of the function
deriv = (func(x+h) - func(x))/h; // I assumed the length to be h
//for second derivative you can use:
second = (func(x+h) - 2*func(x) + func(x-h))/(h*h);
printf("%f\n", deriv);
return 0;
}
The idea is approximate the first derivative of f() at x with the slope of the secant line through the points (x, f(x)) and (x+∆x, f(x+∆x)).
The Wikipedia article should get you started.

Simplified vulgar fractions in C

"How to write an algorithm that, given a number n, prints out all the simplified vulgar fractions that have the denominator 1..n"
(I hope I could phrase it well, feel free to rephrase.)
Example: If n is 3, the output should be like "1/2 1/3 2/3"
We were talking about this question in the end of the last class. He showed us a solution and asked us to try to understand the code. Here it is:
#include<stdio.h>
void main()
{
int p,m,n,i,j,a,b;
p=7;
m=0;
n=1;
do
{
printf("%d/%d\n",m,n);
i=j=1;
for(b=2; b<=p; b++)
{
a=m*b/n+1;
if(a*j<b*i)
{
i=a;
j=b;
}
}
m=i;
n=j;
}
while(i<j);
}
I'm new to C and just learning to code, to be honest I couldn't figure out what this code does. And it also prints "0/1", I also wonder why that is, I think it shouldn't be printing that.
Here is my elementary approach to this problem:
#include <stdio.h>
int gcd(int a, int b) // Finds the GCD of two numbers.
{
int temp;
while (a) {
temp = a;
a = b % a;
b = temp;
}
return b;
}
int main(void)
{
int i, j;
for (i = 1; i <= 7; i++) // Denominator goes from 1 to 7
for (j = 1; j < i; j++) // Numerator goes from 1 to denominator
if (gcd(i, j) == 1)
printf("%d/%d ", j, i); // If the numerator and the denominator
// are coprimes then print the fraction
return 0;
}
"n" is 7 in both of the codes. I checked the execution times with much bigger numbers and my algorithm is faster than the other one. So I don't understand what the other code is for. Also any suggestions/corrections about my code is appreciated.
Your professor's code looks like it may have been purposely complicated, maybe as a learning exercise. If that's the case, I can't say I agree with the practice.
Your approach of nested for loops is exactly how I would have approached the solution.
And it also prints "0/1", I also wonder why that is, I think it shouldn't be printing that.
Simply put, it prints "0/1" because of this line:
printf("%d/%d\n",m,n);
The values m and n are initialized to 0 and 1 right before the do loop, so on the first pass it prints exactly that.
Your code is better than the first paste in a few ways. The loop over b is a crappy way of trying to find a common prime factor for m and n. But it only runs to b=7, so the first program can print 11/121 and other non-reduced fractions!
If the loop over b were properly coded, it would take O(sqrt(n)) time. Your gcd() (using the Euclidean Algorithm well) has O(log(n)) time.
The other code is exceptionally poorly written. Single-letter variables for non-idiomatic uses? void main()? No comments? Nobody should be expected to understand that code, and especially not learners.
Your code seems pretty competent - it's far clearer and cleaner than the other code and pretty much superior in every way. The only suggestion I would make is, firstly, you should take in N as user input from the console, to make rerunning the program for different values simpler, and you should also comment the GCD function explaining it's operations.

Resources