Normal Distribution Calculation having repeated answers and incorrect - c

I'm writing a program that calculates the value of the normal distribution function given to me here:
The program is supposed to ask the user for the mean μ and the Standard Deviation σ for the normal distribution showed above. The program then asks for N values of x and then asks for each value of x, one by one. After each value x it writes out the corresponding value of the function.
This is my code so far:
#define _USE_MATH_DEFINES
#include <stdio.h>
#include <math.h>
int main() {
int j;
double u, stddev, N, result, x;
printf("Enter u and stddev for the Normal Distribution:\n");
scanf("%lf %lf",&u, &stddev);
printf("Enter how many values of x (N) for the Normal Distribution:\n");
scanf("%lf",&N);
for (j=0; j<N; j++) {
printf("Enter a value for x: \n");
scanf("%lf",&x);
result = ((1)/(stddev*sqrt(2*M_PI)))*exp(-(1/2)*((x-u)/stddev)*((x-u)/stddev));
printf("%.6lf\n", result);
}
}
I'm basically done but the answers the program is giving me are wrong when compared to my answers from my calculator. For instance, when I make N = 3 no matter what I put for the 3 values of x, the answer it gives me for each are the same when they shouldn't be.
So I know my issue lies in this line of code:
result = ((1)/(stddev*sqrt(2*M_PI)))*exp(-(1/2)*((x-u)/stddev)*((x-u)/stddev));
Am I just writing the function wrong in the program? I must be, for it not to work.

Your code is clean and functional. Good work so far.
You were correct about which line needed changing - The issue is that using integer division results in an integer, so 1 / 2 results in a value of 0. This can be remedied by using a single double value: 0.5, or by dividing using doubles 1.0 / 2.0.
result = ((1)/(stddev*sqrt(2*M_PI)))*exp(-(0.5)*((x-u)/stddev)*((x-u)/stddev));
I tested out your code after making these changes try it online, and they match up perfectly with the formula on wolfram alpha, as well as what you said in the comments.
For example:
μ=2, σ=3, x=7 results in 0.033159
μ=3, σ=7, x=0 results in 0.051991
μ=4, σ=4, x=4 results in 0.099736

Related

Visual studio code bug

I was a writing a program to invert a 5 digit number in vs code and it goes like this:
// Program to reverse the number
#include <stdio.h>
#include <math.h>
int main()
{
int num, rev_num, a, temp,i;
printf("\nEnter the number to be reveresed: ");
scanf("%d", &num);
a = 0;
for (i = 4; i > (-1); i--)
{
temp = num % 10;
num = (num - temp) / 10;
a = a + temp * pow(10, i);
}
printf("\nThe reverse number is: %d",a);
return 0;
}
One of the input is here:
INPUT PIC
It yielded the output by subtracting 1 from the last digit. Similar is the case with other inputs too.
It yielded the correct output in all the c compilers except vs code. Is there some bug in the vs code or my program is wrong.
You are using a float function for integer purposes.
Getting an off-by-one problem is normal when doing so.
Compare Is floating point math broken?
The dirty details of floats where integers should be used can also easily explain differences between seemingly correct behaviour on one compiler and incorrect results on others.
So, assuming your question is "Is there some bug in the vs code[?] or my program is wrong[?]". I'd say there proabbly is a bug in VSCode (because I simply assume that for any larger program out there...), but not one explaining your observation. The problem is in your code.
In this case it would be easy to keep an increment (*10 instead of +1) number, which goes through values 1, 10, 100, 1000.
The point is to avoid floating points when the input, the output and the logic of the goal is integer.
Most elegantly (by which I mean with least changes to your code) this can be done by calculating a incrementally ("increment" by *10, not by +1). I.e. by multiplying by 10 each loop iteration.
I.e. instead of using pow(), to update a, do:
a = a*10 + temp;
This way, whatever is inside a at the start of the iteration (0 the first time) gets "moved to the left" and the 1-valued digit of the input number, which is found in temp is added.
Because of the way the integer / works you can also simplify the previous line to num = num / 10;, but that line as it is in your code also works fine.
This does not explicitly contain a variable which "increments" 1, 10, 100, it is more that a is going through temporary result values, which are in effect multiplied by 1, 10, 100, ... but the core of the idea is there and I think the minimal change to your code is an advantage of this solution.

Is there a way to write a recursive function that multiplies the even numbers from 1 to n using c?

I've found similar questions that do that to the sums of even numbers, but when i try to change that to the product of these, it always ends up printing out 0.
#include<stdio.h>
int SumEven(int num1, int num2)
{
if(num1>num2)
return 0;
return num1*SumEven(num1+2,num2);
}
int main()
{
int num1=2,num2;
printf("Enter your Limit:");
scanf("%d",&num2);
printf("Sum of all even numbers in the given range is: %d",SumEven(num1,num2));
}
this is an example of one of those i tried to adapt but it only returns 0, any ideas?
You need to post code for a question like this. But the probable cause- when you do a sum, you start with an initial value of 0. When you do products, it needs to be 1. Otherwise you multiply 0*i, which is always 0.
After a bit of thought, I am revising my original answer even though it is a workable solution. Actually, all that you would need to do is change one line of code. Instead of the following linesof code.
if(num1>num2)
return 0;
You just need to do the following.
if(num1>num2)
return 1;
Following were some small limit test results that agreed with manual calculations.
:~/C_Programs/Console/MultEven/bin/Release$ ./MultEven
Enter your Limit:4
Sum of all even numbers in the given range is: 8
:~/C_Programs/Console/MultEven/bin/Release$ ./MultEven
Enter your Limit:8
Sum of all even numbers in the given range is: 384
:~/C_Programs/Console/MultEven/bin/Release$ ./MultEven
Enter your Limit:10
Sum of all even numbers in the given range is: 3840
Try that out.
Regards.

Why does my C program keep giving me 1 as the error?

I ran it, and everything seems to be fine--except that it keeps giving me a margin of error of 1. Why is it doing this?
The program is supposed to prompt the user to input an estimation for the cube root of 3, and it uses Newton's method of approximation to show how many attempts it took to get to the approximation. After 500 attempts or a margin of error less than 0.000001, it's supposed to exit the loop. Why, though, doesn't the margin of error change?
Here's my code:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int main()
{
float a, i, e; //declare float variables
printf("Consider the function f(x) = x^3 - 3 = 0.\n");
printf("Simplifying, we get x^3 = 3.\n");
printf("Simplifying it further, we get x = 3^(1/3).\n");
printf("Enter your estimate of the root: ");
scanf("%f", &a); //prompt user to guestimate
printf("So you're saying that x = %f.\n", a);
i=0; //initiate attempt counter
e=abs((a-pow(3, (1/3)))/pow(3, (1/3))); //margin of error formula
while (e>=0.000001 && i<=500) //initiate while loop with above expressions
{
if (a!=pow(3, (1/3)))
{
printf("Attempt %f: ", i);
a = a - (pow(a, 3) - 3)/(3*pow(a, 2));
printf("%f, ", a);
printf("%f margin of error\n", e);
i=i+1;
}
else
break;
}
}
abs() deals with ints and will return an int, you need fabsf().
In the same way, pow() is for doubles, you should use powf().
Another mistake is writing 1/3 and expecting 0.333... as a result. 1 and 3 are int literals, so the operation performed is integer division. You need to use float literals, such as 1.0f/3.0f.
That's it for type compatibility. I can see another error however : you expect e to somehow remember its formula and reapply it automagically. That's not how imperative languages work : when you write e = something, "something" is calculated and stored in e once and for all. You're doing it correctly for a, now just bring e=abs(...); inside the while loop to update it each time.

"-1.#J" : Strange output in C Program

Somethings I should say: this is the first time I make a question in here. Usually, when I'm with a doubt about something, I found it answered somewhere (including I found a lot of answers in this website). But this time, I'm not finding an answer, so if there was, I didn't find and I'm sorry for making a question that has already been made (I know you guys don't like it, but I promise that I've searched).
I came out with this doubt by helping to sove another person's doubt. Well, I'm not sure how to say this in English, but I believe it is: "standard deviation" (Standard Deviation on Wikipedia). That's what the program is about.
A person came with a question how to do this, it wasn't working... I didn't know the formula to calculate the standard deviation, but he gave to me. But the one he gave was wrong. I'll show the code of how the program is: PasteBin of My Standard Deviation Code
It seems to be working now with this way I did, but I'm not sure. I gave this solution to the person who asked my help. Is the program right?
But my real question is not if the program is right. There is this part on the code:
sum += pow(v[i] - m,2);
When he gave me the wrong formula it was:
sum += v[i] - m;
Can you guys compile that wrong code? Depending on the numbers that you put, the output is -1.#J. Why's that? What does this mean?
#include <stdio.h>
#include <math.h>
int main (void)
{
int n = 10, i;
double d, m = 0.0f, sum = 0.0f, v[10];
for (i = 0; i < n; i++)
{
printf ("Inform a real number: ");
scanf ("%lf",&v[i]);
m += v[i];
}
m /= n;
for (i = 0; i < n; i++)
sum += pow(v[i] - m,2);
d = sqrt (sum/(n-1));
printf ("The standard deviation of vector v is = %.2lf\n\n",d);
return 0;
}
1.#J is Microsoft's strange way of displaying infinity. This is a special floating-point value that results from dividing by zero or from numeric overflow.
I can't figure out why you're getting it, though. What inputs are you entering that give you the strange output?
m /= n;this is the average
d = sqrt (sum/(n-1));but why this place use n -1,I think it should be n
now why the output is -1.#j:
This is because the float you input is not right(I mean your input is not a float),example you input ad,I think the output is random if the input is wrong.
If you are not compiling your program in C99/11 mode then the program's behavior is undefined, you can get anything. A double type data is printed by using %f format specifier.
printf ("The standard deviation of vector v is = %.2lf\n\n",d);
^
| Wrong specifier
7.21.6 Formatted input/output functions:
If a conversion specification is invalid, the behavior is undefined.282) If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.
Also change
double d, m = 0.0f, sum = 0.0f, v[10];
line to
double d, m = 0.0, sum = 0.0, v[10];
m and sum are of double type, no need to put f for forcing that it is a float type.

Incorrect formula?

So here is a program that is supposed to calculate an approximation to the value of pi if you take enough terms into the sum which is mathematically described in the following program and calculates the expression of the root, you get a value that gets closer and closer to the value of pi the more terms you have.
#include <stdio.h>
#include <math.h>
main()
{
int j, terms;
double sum, precision, pi;
printf("How many terms: "); scanf("%d", &terms);
for(j=1;j<=terms;j++)
sum+=1/(j*j);
pi = sqrt(6*sum);
printf("Pi: %lf.\n", pi);
}
But there is something making it go wrong here and I can't quite figure out what.
sum+=1/(j*j);
I thought the mistake might be in that line because all others look fine,thinking at first maybe the computer isn't counting decimals.I'm unsure.But my question is: What is it in this code that makes it malfunction?And how do I fix it?
This performs integer division:
1/(j*j);
try this:
sum+=1.0/(j*j);
If j*j might overflow, do this
sum+=1.0/((double)j*j);

Resources