I'm trying to code a formula where the user inputs a number n to calculate Pi using Pi= n^2/(n-1)(n+1). But for some reason the output is wrong. I don't know if my math is wrong or there's something wrong with the function.
Here is the code :
#include <stdio.h>
#include <math.h>
double pi_array (int n)
{
int i;
double a;
if (n%2==0)
{
for (i=2;i<=n;i+=2)
{
a=pow(n,2)/((n-1)*(n+1));
}
}
return a;
}
double pi_value (int n)
{
int i;
double pi;
for (i=0;i<=n;i++)
{
pi=pi_array(n);
}
return pi;
}
void main()
{
int n;
scanf("%d",&n);
printf ("%lf\n", pi_value(n));
}
Just like #Mat pointed out, in this part of your code:
for (i=2;i<=n;i+=2)
{
a=pow(n,2)/((n-1)*(n+1));
}
It is doing the same computation again and again because n does not change its value. The answer pow(n,2)/((n-1)*(n+1)) remains the same even for all the iterations.
Also, on a side note, what formula are you using to calculate your answer? If you put n = 4, you get the value as 16/15 which equals 1.0667. For n = 5, the asnwer is 1.041667. They are clearly not equal to pi. I think thew formula might be wrong itself. You could post the question about the formula on MathStackExchange to get an idea of what the exact formula is, and then implement it in C later :).
Best.
Related
So I am trying to run this code where I calculate the mean and median in 2 functions. When I use these functions in my main function and run my program, sometimes it gives me the right answer and sometimes it gives me some random numbers for the mean even though I run the exact same code. Can somebody explain this behavior to me?
Any help is appreciated.
float mean(int *numbers, int n){
int i=0;
float solution;
float tmp_m;
for(i=0; i<n; i++){
tmp_m=(float)numbers[i]+tmp_m;
}
solution=tmp_m/((float)n);
return solution;
}
float median(int *numbers, int n){
float median;
float median_b;
int index;
int index_b;
if(n % 2 == 1){
index=n/2;
median= (float)numbers[index];
return median;
}else if (n % 2 == 0){
index_b=n/2;
float tmp_median;
tmp_median= (float)numbers[index_b] + (float)numbers[index_b-1];
median_b=tmp_median/((float)2);
return median_b;
}
}
#include <stdio.h>
int main () {
int array[6]={0,2,3,4,0,5};
int n=6;
float result=mean(array, n);
float result_median=median(array, n);
printf("%f\n%f\n", result, result_median);
return 0;
}
The variable tmp_m is left uninitialized and it gives you random values.
So, replace float tmp_m; with float tmp_m = 0; in the mean function.
You haven’t initialised tmp_m to zero before using it.
Your tmp_m is not initialized to 0, so it starts out as a random number, which results in an incorrect result
This factorial function starts giving wrong results with 13 and above. I have no idea why.
#include <stdio.h>
int fatorial (int p);
int main() {
int x = 13;
int test = fatorial(x);
printf("%d", test);
}
int fatorial (int p) {
if (p <= 0)
return 1;
else
return p*fatorial(p-1);
}
for x = 0, 1, 2 ...12 it prints the right result, but for 13! it prints 1932053504 which is not correct.
For x=20 it prints -210213273 for example.
I know that this is not the best way to do a factorial. Its my homework tho, it HAS to be this way.
If you try this you will get the maximum value that int can hold:
#include <stdio.h>
#include <limits.h>
int main(void)
{
printf("%d\n", INT_MAX);
}
Your code causes overflow.
You could get a few more numbers if you use a bigger type, but not by very much. You could use this:
unsigned long long fatorial (unsigned long long p) {
if (p <= 0)
return 1;
else
return p*fatorial(p-1);
}
It won't get you far though. If you want bigger than that you need to find a library for bigger integers or create some custom solution. One such library is https://gmplib.org/ but that is likely out of scope for your homework.
And btw, a condition like p <= 0 is not good. It indicates that the factorial of a negative number is always one, which is false.
It is because after 12, the result of factorial of any number exceeds the size of int.
you can try the following code:
#include<stdio.h>
int main()
{
int a[100],n,counter,temp,i;
a[0]=1;
counter=0;
printf("Enter the number: ");
scanf("%d",&n);
for(; n>=2; n--)
{
temp=0;
for(i=0; i<=counter; i++)
{
temp=(a[i]*n)+temp;
a[i]=temp%10;
temp=temp/10;
}
while(temp>0)
{
a[++counter]=temp%10;
temp=temp/10;
}
}
for(i=counter; i>=0; i--)
printf("%d",a[i]);
return 0;
}
The result of the function is too big. I think big int would work better for your purposes. Big int allows you to have bigger numbers. Also, this is what I would do.
int x = the number you want to factorialize
int ans = 1;
(Then instead of all of those functions)
for(var i = x; i > 0; i--) {
ans = ans*i;
}
System.out.println(ans);
Javascript link: https://jsfiddle.net/8gxyj913/
I need to get to 100!
100! is about 9.332622e+157. Simply using standard integer types is insufficient. 32-bit int is good to 12!. With 64-bit integer math, code could get to about 21!
Could use floating point math and give up precision.
Instead consider a string approach.
I've put an printf to check if the function works, but i cant figure out why it doesnt work.
The numbers are all correct in functions, but they dont get executed.
I am not sure why the function isn't working, i dont have much knowledge in C so if anyone could help me that would be much appreciated.
The program is supposed to calculate the odds of you passing the test, by calculating the odds of the people around in your class room.
Example:
P
NXNXNXNXN
ZNZNXXXXX
XNZXNNNZX
ZNXHXXXXZ
NNNNZNNXN
P - professor
Z - prepared student
N - unprepared student
X - an empty seat
H - Me
Input:
3 4
2 50
X X X X
Z H N X
Z N X X
Expected Output:
Sanse za prolaz su 62.50%
Output gotten:
Sanse za prolaz su -0.00
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
///FUNKCIJA POSTOTAK
float fudaljenost(int visina, int sirina,char array[visina][sirina])
{
float postotak=0;
float udaljenostx=0,udaljenosty=0,udaljenost=0;
int Hx,Hy;
int Zx,Zy;
int Nx,Ny;
for(int i=0;i<visina+1;i++)
{
for(int j=0;j<sirina;j++)
{
if(array[i][j]=='H')
{
Hx=i;
Hy=j;
}
}
}
for(int i=0;i<visina+1;i++)
{
for(int j=0;j<sirina;j++)
{
if(array[i][j]=='Z')
{
Zx=i;
Zy=j;
udaljenostx=abs(Hx-Zx);///A
udaljenosty=abs(Hy-Zy);///B
printf("Z A=%f B=%f\n",udaljenostx,udaljenosty);
udaljenost=sqrt((udaljenostx*udaljenostx)+(udaljenosty*udaljenosty));///UDALJENOST
postotak+=90/(udaljenost*udaljenost);///POSTOTAK
}
}
}
for(int i=0;i<visina+1;i++)
{
for(int j=0;j<sirina;j++)
{
if(array[i][j]=='N')
{
Nx=i;
Ny=j;
udaljenostx=abs(Hx-Nx);///A
udaljenosty=abs(Hy-Ny);///B
printf("N A=%f B=%f\n",udaljenostx,udaljenosty);
udaljenost=sqrt((udaljenostx*udaljenostx)+(udaljenosty*udaljenosty));///UDALJENOST
postotak-=30/(udaljenost*udaljenost);///POSTOTAK
}
}
}
return postotak;
}
///FUNKCIJA PROFESOR
float fprofesor(float strogost,int visina, int sirina,char array[visina][sirina])
{
float postotak=0;
int Hx,Hy;
int Px,Py;
float udaljenostx=0,udaljenosty=0,udaljenost;
for(int i=0;i<visina+1;i++)
{
for(int j=0;j<sirina;j++)
{
if(array[i][j]=='H')
{
Hx=i;
Hy=j;
}
}
}
for(int i=0;i<visina+1;i++)
{
for(int j=0;j<sirina;j++)
{
if(array[i][j]=='P')
{
Px=i;
Py=j;
udaljenostx=abs(Hx-Px);///A
udaljenosty=abs(Hy-Py);///B
udaljenost=sqrt((udaljenostx*udaljenostx)+(udaljenosty*udaljenosty));///UDALJENOST
postotak=strogost/(udaljenost*udaljenost);///POSTOTAK
}
}
}
return postotak;
}
int main()
{
int i=0,j=0;
int visina,sirina;
int prof;
float strogost;
float posto1,posto2,posto;
char Ucionica[50][50]={0};
float postotak=0;
float udaljenostx=0,udaljenosty=0,udaljenost=0;
int Hx,Hy;
int Zx,Zy;
int Nx,Ny;
scanf(" %d%d",&visina,&sirina);
scanf(" %d%f",&prof,&strogost);
///UPIS MATRICE
for(i=1;i<visina+1;i++)
{
for(j=0;j<sirina;j++)
{
scanf(" %c",&Ucionica[i][j]);
}
}
Ucionica[0][prof-1]='P';
posto1 = fudaljenost(visina,sirina,Ucionica);
posto2 = fprofesor(strogost,visina,sirina,Ucionica);
posto = posto1-posto2;
printf("Sanse za prolaz su %.2f",posto);
return 0;
}
Stackoverflow isnt allowing me to post this without adding more words, so im using this part of the text to add more words, sorry stackoverflow for going around the system like this but im kinda running out of time on this.
The current code passed cast on a main variable char Ucionica[50][50]={0} into a function that expects a prototype of float fprofesor(float strogost,int visina, int sirina,char array[visina][sirina]).
From the context, it looks as if the [50],[50[ represent the largest possible input size, but the program will use only the first few rows/columnns (3, 4 in the example). Regardless of how much data will be used, the definition in the called functions should match the data size.
float fprofesor(float strogost,int visina, int sirina,char array[50][50]) { ... }
float fudaljenost(int visina, int sirina,char array[50][50]) { ... }
Side note, gcc -Wall flaggedd many warning on unused variables, but no warning in passing array with mismatch minor array size
Also, probably a good idea to '#define' the maximum size, instead of hardcoding 50 repeated times.
The functions were written wrong,
in
float fudaljenost(int visina, int sirina,char array[visina][sirina])
It wasn't the same size array as sent before[50][50]
The following will fix the problem:
float fudaljenost(int visina, int sirina,char array[50][50])
float fprofesor(float strogost,int visina, int sirina,char array[50][50])
Worth noting that it will be better to #define MAX_ARRAY_SIZE 50, and use MAX_ARRAY_SIZE instead of 50. This will make it easier to avoid error if the number will need to be changed, and will provide hint on what the 50 is.
I'm trying to code the Riemann Zeta function in C but I'm having quite issues with the negative odds one. Since Even negatives are 0 by definition. Only for Real numbers the function, not complex. So 0..1 it's undefined. I know it's some math error I'm doing, but I started today to read about this function and I'm trying to learn.
https://en.wikipedia.org/wiki/Riemann_zeta_function
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
double zeta(double s, long long int n)
{
double p=0.0;
if(s<0 && fmod(s,2)==0)
{
return p;
}
if(s==0) { return -0.5;}
if(s>0 && s<=1)
{
puts("Undefined. ");
exit(-1);
}
long long int i;
for(i=n; i>0; i--)
{
p+=pow(i,-s);
}
return p;
}
int main()
{
double s;
puts("Enter real number to Zeta function: ");
scanf("%lf",&s);
printf("\n%.15lf",zeta(s,1000000));
return 0;
}
It's just a sketch... Nothing professional here!
example: zeta(-5) = -0.003968253968253
it's giving 1.036927755143338...
I'm only having issues with NEGATIVE REAL ones...
I'm on Windows 10, Codeblocks with GCC.
The code was update with the #NPE contributions but still not working for negative real odds...
I did not participate in comments, sorry.
following the definition of the zeta-function the simple way of coding is (I just changed s to -s from your code, and added the 'level of convergence n' as a parameter)
double zeta_simple(double s, long long int n)
{
double p=0.0;
long long int i;
for(i=1; i<=n; i++)
{
p+=pow(i,-s);
}
return p;
}
However the problem is that you start adding the "big" numbers before the "small" and soon you will hit underflow operation. So what you want to do is
double zeta(double s, long long int n)
{
double p=0.0;
long long int i;
for(i=n; i>0; i--)
{
p+=pow(i,-s);
}
return p;
}
you can test convergence with s=2 which converges to PI^2/6.0 and s=4 which converges to PI^4/90.0
#define PI 3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679L
int main()
{
long long int n;
for (long long int n=10; n<=100000000; n*=10)
{
printf("%28.16f\t %28.16f\n", zeta(4.0, n), zeta2(4.0, n));
}
printf("%s=%20.16f\n\n","PI^4/90", PI*PI*PI*PI/90.0);
for (long long int n=10; n<=10000000000; n*=10)
{
printf("%28.16f\t %28.16f\n", zeta(2.0, n), zeta2(2.0, n));
}
printf("%s=%20.16f\n","PI^2/6 ", PI*PI/6.0);
}
you get
1.0820365834937564 1.0820365834937566
1.0823229053444732 1.0823229053444725
1.0823232333783044 1.0823232333783073
1.0823232337108049 1.0823232337108359
1.0823232337111379 1.0823232337109849
1.0823232337111381 1.0823232337109849
1.0823232337111381 1.0823232337109849
1.0823232337111381 1.0823232337109849
PI^4/90= 1.0823232337111379
1.5497677311665408 1.5497677311665408
1.6349839001848929 1.6349839001848925
1.6439345666815597 1.6439345666815606
1.6448340718480596 1.6448340718480665
1.6449240668982261 1.6449240668982523
1.6449330668487265 1.6449330668487985
1.6449339668482315 1.6449339668477756
1.6449340568482265 1.6449340573291047
1.6449340658482263 1.6449340600880324
1.6449340667482264 1.6449340600880324
PI^2/6 = 1.6449340668482264
see how the convergence of zeta_simple stops after a while... For convergence to continue you have to use zeta
You can also see that for 10000000000 operations (hence the use of long long int) you only get a precision on 9 digits for s=2. And as s increase so does the rate of convergence.
Therefore for small s to be efficient people use accelerated convergence formulae.
If you want to dig further I recommend you look at https://math.stackexchange.com/questions/183680/modern-formula-for-calculating-riemann-zeta-function
Also wat is really interesting is when you start poking around with s complex
Im trying to make a program that calculates out a math equation, Im getting stuck on how i generate a random number from 0.00 to 1.00 and store it in a variable a.
this is my code so far, im stuck to how now take that number and store it for future use. I need to store that random number in a, and hten use it in a loop, and then generate a new random number and use it in the 2nd cycle of the loop.
EDIT
this is what i have been working on now, it is suppose to calculate the number of times a random number is inside the area, count it, and then devide by the number of times run, but im not getting any output
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
void initrand(void)
{
srand(time(0));
}
float randfloat(void)
{
return rand()/(float)RAND_MAX;
}
int main(void)
{
int n = 10;
float x;
float y;
float pi = 3.1415;
float rootxy;
initrand();
int z = 0;
int inside = 0;
x = randfloat();
y = randfloat();
float area = 0.25 * pi;
float calculatedpi;
rootxy = sqrt(pow(x,2) + (pow(y,2)));
while (z < n){
if (rootxy > area) {
inside++;
z++;
}
else{
return 0;
}
calculatedpi = (inside/n);
}
printf("%f", calculatedpi);
}
There are a few issues with your code:
You shouldn't use nested functions. Some compilers support them as an extension but it's not standard. Define randfloat and initrand outside main
The function initrand does too little. Why not call srand((time(0)); from main ?
Your initrand function is declared as returning a double but it doesn't return anything (and the way it's named it shouldn't). If you need to use such a function, why not make it return void ?
You should rarely use float. Why not use double ?
That said, you can do this to store that random value:
double randdouble()
{
return rand()/((double)RAND_MAX + 1);
}
int main()
{
double x = randdouble();
/* ... */
}
I think you want something like this:
#include <stdlib.h>
#include <time.h>
void initrand(void)
{
srand(time(0));
}
float randfloat(void)
{
return rand()/(float)RAND_MAX;
}
int main(void)
{
initrand();
float a = randfloat();
return 0;
}
You can't nest functions like in some other languages.
You had non-matching parentheses in the initrand function.
I fixed the declarations of your functions, use void when there are no parameters, initrand doesn't return anything.
Your division by RAND_MAX+1 was a little messed up. Simply divide by RAND_MAX and the result will be in the closed interval [0,1]. And the syntax for the conversion to float was not quite right.
If you want to get random double numbers in a specified range you can use this function
// Return a random double from a to b
double randomDouble(double a, double b)
{
return = ( rand() / ( (double)RAND_MAX + 1.0))
* (b - a) + a;
}