Fractions: Sum and difference in C programming - c

I'm facing problems in writing a program in C that calculates S, being S = {1/50 - 3/48 + 5/46...} with 9 elements. I don't know how to use the DIFFERENCE operator followed by a SUM operator, and I MUST use the for structure.
Here's the program I wrote:
#include <stdio.h>
#include <stdlib.h>
int main (void) {
int n, d, S, i;
i = 0;
n = 1;
d = 50;
S = n / ((double)d);
for (i = 0; i < 4; i++) {
n += 2;
n -= 2;
S = S + (n / ((double)d));
S = S - (n / ((double)d));
}
printf("%d", S);
return 0;
}
I know that the variable declarations may be wrong and that's exactly where I get confused. I decalred S as an integer but put d (denominator) to double 'cause the result must be a decimal number, of course.
Can anybody help me??
The output I'm getting is: 0

Perhaps like this. The most important point, is to use the double type, because the int type can only hold whole numbers.
#include <stdio.h>
int main (void) {
int i;
double sign = 1.0; // sign
double num = 1.0; // numerator
double div = 50.0; // divisor
double sum = 0.0; // series sum
for (i = 0; i < 9; i++) {
sum += sign * num / div; // accumulate the term
num += 2.0; // numerator +2
div -= 2.0; // divisor -2
sign *= -1.0; // alternate the sign
printf("%f\n", sum); // show double result
}
return 0;
}
Program output:
0.020000
-0.042500
0.066196
-0.092895
0.121390
-0.153610
0.188496
-0.228171
0.271829

Different things to say about your code.
First you cannot use an integer for your sum since you want a floating point result.
Then as mentioned in comments you are using successive operations that result in not changing the variable
n+=2; n-=2;
You could simply do something like :
double S = 0.0; int N=9;
for(i=0; i < N; ++i) {
S += ( (i % 2 == 0)?(1.0):(-1.0) ) * (2.0*i+1)/(50-(2.0*i+1));
}
The instruction (i % 2 == 0)?(1.0):(-1.0) pick 1 if 'i' is even and -1 if 'i' is odd.
Finally if S is no longer an int you must change your printf with a floating point format like for example '%f'.

Check if what you're looking for is the following code:
#include <stdio.h>
#include <stdlib.h>
void main () {
int n = 1, d = 50, i = 0, signal = 1;
double S = n / (double) d;
for (i = 0; i < 8; i++) {
n += 2;
d -= 2;
signal = -signal;
S += signal * n/(double)d;
}
printf("%f", S);
}
I think you're missing S is a double number. int/double = double, but youre assign this math in a int variable.

Related

Finding minimum of a function with N variables

I'm trying to code an algorithm to locate the minimum of Rosenbrock function that may have N variables. When N = 2, I can easily figure it out. The code that I'm using for N = 2 is below:
double y,z,x, aux1, aux2;
double menor = INT_MAX;
y = INT_MIN;
x = INT_MIN;
while(x < INT_MAX)
{
while(y < INT_MAX)
{
z = (1-x)*(1-x) + 100*(y - (x*x))*(y - (x*x));
if(menor > z)
{
menor = z;
aux1 = x;
aux2 = y;
}
y = y + 0.1;
}
y = 0.1;
x = x + 0.1;
}
printf("(x,y) : (%.2lf, %.2lf) Minimum value of z: %.2lf\n", aux1, aux2, menor);
This code is working fine and I'm summing y and x by 0.1 only because I already know what the minimum is given that function (it's on (1,1)). It takes a little while to run, but it works. My problem is for N variable. When I think about this, what comes to my mind is that I will need N repetition structures. Here is the code as it's by now. Its not working, but it may give some idea of what I'm trying to do:
//Calculates the value of the Rosenbrock function given n(the number of variables)
double rosen(double *x, int n){
double y;
for(int i = 0; i < n-1; i++)
{
y = y + 100*((x[i+1] - x[i]*x[i])*(x[i+1] - x[i]*x[i])) + (1 - x[i])*(1 - x[i]);
}
return y;
}
int main(void){
double *x;
//n is the number of variables and it may change
int n = 3;
x = (double*)malloc(n * sizeof(double));
double rosen(double *x, int n);
for(int i = 0; i < n; i++)
{
x[i] = INT_MIN;
}
//That's the part where I can't figure out how to compute all the possibilities, changing the value of the last variable between INT_MIN AND INT_MAX. Then this variable gets the value of INT_MIN again and I will sum 0.1 to the variable antecedent, and then do all the process again to the last variable. And so on for all the N variables.
for(int i = n - 1; i >= 0; i--)
{
while(x[i] < INT_MAX)
{
x[i] = x[i] + 0.1;
}
x[i] = INT_MIN;
}
This code above probably contain some erros. But, the only thing I'm needing help is to vary all the values of the N variables. So, what I want to do is take the last variable and vary its value between INT_MIN and INT_MAX, summing 0.1(I know its really a long journey). After that, this variable will receive INT_MIN value again and the antecedent variable will vary by +0.1. Then, the last variable will vary from INT_MIN to INT_MAX again. And this will happen for all the N variables.
This is a problem that I'm trying to solve, to brute-force the value of a function to get its minimum. If you guys have some tips for me or some library that may help, I will be very gratefull.
You can have a recursive function like the following (rough C):
void rosenMin(int maxDims, int currDim, double[] values, double* currMin)
{
if (currDims == maxDims) {
double rosenVal = rosen(values); // You need to implement this
if (rosenVal < *currMax) {
*currMin = rosenVal;
}
} else {
for (double c = INT_MIN; c <= INT_MAX; c += 0.1) {
values[currDim + 1] = c;
rosenMin(maxDim, currDim + 1, values, currMin);
}
}
}
double[] values = new double[N] { 0 }; // Check with C syntax how this'll look!
double min = INT_MAX
rosenMin(N, 1, values, &min);

First real program in C: Fibonacci sequence

I'm trying to write the first 10 terms of the Fibonacci sequence. I feel like I'm on the right line, but I can't seem to quite grasp the actual code (in C).
float fib = 0;
const float minn = 1;
const float maxn = 20;
float n = minn;
while (n <= maxn);{
n = n + 1;
printf (" %4,2f", fib);
fib = (n - 1) + (n - 2);
}
With the fibonacci sequence the value f(n) = f(n - 1) + f(n = 2). the first three values are defined as 0, 1, 1.
The fibonacci sequence is a sequence of integer values (math integers, not necessarily C language values). consider using int or long for the fibonacci value. float is worthless, it only adds unneeded overhead.
when calculating the fibonacci sequence you must store the previous 2 values to get the next value.
you want 10 fibonacci values. you know the first three already so print those and then calculate the next seven values.
7 values implies a loop that iterates 7 times. it has no bearing on the maximum value of the fibonacci value returned, just how many values you want to print.
do something like this:
printf("0, 1, 1");
int currentValue;
int valueN1 = 1;
int valueN2 = 1;
for (int counter = 1; counter <= 7; ++counter)
{
currentValue = valueN1 + valueN2;
printf(", %d", currentValue);
valueN2 = valueN1;
valueN1 = currentValue;
}
You need run loop 10 times only,to find first 10 terms of the Fibonacci sequence.
in your code,while loop would not let you go further because of semicolon at the end of loop
//declare fib value as long int or unsigned int
// because the value of any fib term is not at all
long int fib;
int n=1;
while (n <= 10)
{
printf (" %d", fib);
fib = fib_term(n);
n = n + 1;
}
implement fib_term(int n); by seeing this snippet
First off, I would suggest changing your datatype from a float to an integer or other datatype. floats are not exact numbers and if you had used while (n = maxn) instead of while (n <= maxn) you could have ended up with an infinite loap since the two floats would never have matched.
Second, you don't seem to really understand what the fibonacci sequence is. Take a look at the wikipedie article http://en.wikipedia.org/wiki/Fibonacci_number.
The fibinocci number is NOT (n - 1) + (n - 2) like you have. It is the sum of the previous two numbers in the sequence. You need to restructure your loop to hold the last two values and calculate the next one based on these values.
There are (at least) 2 ways to implement the Fibonacci Algorithm in C:
The Iterative:
int fib(int n){
if (n == 0)
return 0;
int a = 1
int b = 1;
for (int i = 3; i <= n; i++) {
int c = a + b;
a = b;
b = c;
}
return b;
}
The Recursive:
unsigned int fibonacci_recursive(unsigned int n)
{
if (n == 0)
{
return 0;
}
if (n == 1) {
return 1;
}
return fibonacci_recursive(n - 1) + fibonacci_recursive(n - 2);
}
void main(){
unsigned int i = fibonacci_recursive(10);
}
Suggestions
Consider integer types before FP types when doing integer problems.
Omit a ; in your while (n <= maxn);{
Use a . in floating point formats %4.2f instead of %4,2f.
Fibonacci is the sum of the previous 2 terms, not simply fib = (n - 1) + (n - 2).
Consider an unsigned solution:
C code:
void Fibonacci_Sequence(unsigned n) {
const unsigned minn = 1;
const unsigned maxn = 20;
unsigned F[3];
F[0] = 0;
F[1] = 1;
unsigned i = 0;
for (i = 0; i <= maxn; i++) {
if (i >= minn) printf(" %u,", F[0]);
F[2] = F[1] + F[0];
F[0] = F[1];
F[1] = F[2];
}
}
This uses n/2 iterations
#include<stdio.h>
main()
{
int i,n,a=0,b=1,odd;
scanf("%d",&n);
odd=n%2;
for(i=1;i<=n/2;i++)
{
printf("%d %d ",a,b);
a=a+b;
b=a+b;
}
if(odd)
printf("%d",a);
}

C - Sum of numbers

Why won't my program work? It is supposed to add numbers from a formula 1-(1/2)+(1/3)...+(1/999)-(1/1000)=
#include <stdio.h>
#include <math.h>
int main () {
int i, j;
float suma;
suma = 0.f;
for (i=0; i<1000; i++) {
if (i%2==0) {
suma=suma - 1/i;
} else {
suma=suma + 1/i;
}
}
printf("%f", suma);
}
Divide by zero !!
int main () {
int i;
float suma;
suma = 0.0f;
for (i=1; i<1000; i++) { //fix loop, start from 1
if (i%2==0) {
suma=suma - 1.0f/i; // Use 1.0, (1/i will be evaluated as int)
} else {
suma=suma + 1.0f/i;
}
}
printf("%f", suma);
}
Try printing 1 / i with i being an int. This will always returns 0, except when i is 1. This happens because 1 / i is evaluated as an Euclidean division with the remainder being discarded.
The reason this is evaluated like this is because 1 and i are both integer.
You need to either the numerator or the denominator to be of floating point type.
One way is to cast i to a float, so your code would look like this: suma = suma - 1 / (float)i. The other way is to make 1 be of floating point type: suma = suma - 1.0 / i or suma = suma - (float)1 / i.
The for loop started from 0.
so the first iteration returns divide by zero error.
second iteration will return 1/1=1 and will work good, but from third iteration it will return 0, because you are using int. Try starting the for loop from 1 and typecast i to float.
You will get much higher accuracy if you apply some math first. Your series:
1 - 1/2 + 1/3 - 1/4 + ... + 1/999 - 1/1000
can be rewritten as:
(1 - 1/2) + (1/3 - 1/4) + ... + (1/999 - 1/1000)
or as:
1/(1*2) + 1/(3*4) + ... + 1/(999*1000)
Now, you can write a program to perform calculation. However, you should use double type to improve accuracy and cast integer to double to make sure that your series are added as double numbers:
#include <stdio.h>
#include <math.h>
int main() {
int i;
double sum = 0;
for (i=1; i<1000; i+=2) {
sum += 1/(i*(i+1.)); // 1. to force cast to double
}
printf("%g", sum);
}
herein a simple program
float j = 1.0f;
float suma = 0.0f;
int i = 1;
for (i=1; i <= 1000; i++) {
suma += j/i;
j = j * (-1);
}

Converting an int array to an int value in c

I have an integer array
int number[] = {1,2,3,4};
What can I do to get int x = 1234?
I need to have a c version of it.
x = 1000*number[0] + 100*number[1] + 10*number[2] + number[3];
This is basically how decimal numbers work. A more general version (when you don't know how long 'number' is) would be:
int x = 0;
int base = 10;
for(int ii = 0; ii < sizeof(number); ii++) x = base*x + number[ii];
Note - if base is something other than 10, the above code will still work. Of course, if you printed out x with the usual cout<<x, you would get a confusing answer. But it might serve you at some other time. Of course you would really want to check that number[ii] is between 0 and 9, inclusive - but that's pretty much implied by your question. Still - good programming requires checking, checking, and checking. I'm sure you can add that bit yourself, though.
You can think of how to "shift over" a number to the left by multiplying by ten. You can think of appending a digit by adding after a shift.
So you effectively end up with a loop where you do total *= 10 and then total += number[i]
Of course this only works if your array is digits, if it is characters you'll want to do number[i] - '0' and if it is in a different base you'll want to multiply by a different number (8 for instance if it is octal).
int i = 0, x = 0;
for(; i < arrSize; i++)
x = x * 10 + number[i];
x is the result.
int i;
int x = 0;
for ( i = 0; i < 4; i++ )
x = ( 10 * x + number[i] );
int number[]={1,2,3,4}
int x=0,temp;
temp=10;
for(i=0;i<number.length;i++)
{
x=x*temp+number[i];
}
cout>>x;
You could do something with a for loop and powers of 10
int tens = 1;
int final = 0;
for (int i = arrSize - 1; i <= 0; ++i)
{
final += tens*number[i];
tens*=10;
}
return final;
Answer is quite easy.Just list a complete function here.
int toNumber(int number[],arraySize)
{
int i;
int value = 0;
for(i = 0;i < arraySize;i++)
{
value *=10;
value += number[i];
}
return value;
}

How to take a moving mean of an array

Can some one please help me on this issue as I have spent time going around it without making any headway.
I have data in an array of size say 3O.
I want to take the first five elements of the array, find their mean value. Store the value in another array
Then move to the second element of the array,from their find the mean value of the 5 succeeding elements.store the value in the array as above.
Then wove to the 3rd element,do the same thing above till the last element which is 30 in this case.
float tabdata[] = {1,2,3,4,...,30};
char *store;
float sum;
for(int j=0;j<tabdata[30-1];j++)
sum += tabdata[j];
if (j=5)
{
float mean= sum/5;
store[j]=mean;
sum=0;
for(i=j;i>tabdata[30-1];i++)
sum +=tabdata[i];
if (j=5)
---
----
....need help to complete this loop please.
Just add 1/5 of the next element and subtract 1/5 of the first element in the current window at every step. The only thing you need to worry about is floating point precision.
You can fix up the sum as you go:
#include <stdlib.h>
#include <stdio.h>
int main()
{
float tabdata[] = {1,1.5,1.8, 2, 3, 4, 5,6,7,8,9,10,11,12,13,14,15,161,7,18,19,20,21,30};
float* result;
float sum;
int count = sizeof(tabdata)/sizeof(tabdata[0]);
int i;
result = (float *)malloc((count - 4) * sizeof(float));
/* Initialise with the first five elements */
for (i=0;i<5;i++)
{
sum += tabdata[i];
}
result[0] = sum / 5.0;
for (i=5;i<count;i++)
{
sum -= tabdata[i-5];
sum += tabdata[i];
result[i-4] = sum / 5.0;
}
for (i=0;i<count-4;i++)
{
printf("%f\t%f\n",tabdata[i],result[i]);
}
for (;i<count;i++)
{
printf("%f\n",tabdata[i]);
}
free(result);
}
I think that what you might want to use is the modulus operator (%) which will give you the rest of the division. You will get something like this:
if ((j+1) % 5 == 0)
{
float mean= sum/5;
store[j/5]=mean;
sum=0;
}
This way, at every 5 iterations, the code will be executed.
Haven't tested this but should work:
float tabdata[] = {1, 2, 3, ..., 30};
float *result;
float sum;
int count = sizeof(tabdata)/sizeof(tabdata[0]);
result = (float *)malloc((count - 4) * sizeof(float));
for (int j = 0; j < count - 5; j++) {
sum = 0;
for (int k = j; k < j + 5; k++) {
sum += tabdata[k];
}
result[j] = sum / 5;
}
// ...
free(result);

Resources