-use double precision
-use sqrt() and exponential function exp()
-use * to compute the square
-do not use pow()
I am getting values they are just not anything as to what I expected. I tried making them all signed but it didn't change anything and I've tried printing out with 12 decimal places and nothing seems to be working.I have linked the math library and defined it as well.
double normal(double x, double sigma, double mu)
{
double func = 1.0/(sigma * sqrt(2.0*M_PI));
double raise = 1.0/2.0*((x-mu)/sigma);
double func1 = func * exp(raise);
double comp_func = (func1 * func1);
return comp_func;
}
int main(void)
{
// create two constant variables for μ and σ
const double sigma, mu;
//create a variable for x - only dynamic variable in equation
unsigned int x;
//create a variable for N values of x to use for loop
int no_x;
//scaniing value into mu
printf("Enter mean u: ");
scanf("%lf", &mu);
//scanning value into sigma
printf("Enter standard deviation: ");
scanf("%lf", &sigma);
//if sigma = 0 then exit
if(sigma == 0)
{
printf("error you entered: 0");
exit(0);
}
//storing number of x values in no_x
printf("Number of x values: ");
scanf("%d", &no_x);
//the for loop where i am calling function normal N times
for(int i = 1; i <= no_x; i++)
{
//printing i for the counter in prompted x values
printf("x value %d : ", i);
// scanning in x
scanf("%lf", &x);
x = normal(x,sigma,mu);
printf("f(x) = : %lf.12", x);
printf("\n");
}
return 0;
}
C:>.\a.exe
Enter mean u: 3.489
Enter std dev s: 1.203
Number of x values: 3
x value 1: 3.4
f(X) = 0.330716549275
x value 2: -3.4
f(X) = 0.000000025104
x value 3: 4
f(X) = 0.303015189801
But this is what I am receiving
C:\Csource>a.exe
Enter mean u: 3.489
Enter standard deviation: 1.203
Number of x values: 3
x value 1 : 3.4
f(x) = : 15086080.000000
x value 2 : -3.4
f(x) = : 15086080.000000
x value 3 : 4
f(x) = : 1610612736.000000
Insert these lines:
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
Change:
const double sigma, mu;
to:
double sigma, mu;
Change:
unsigned int x;
to:
double x;
Replace the definition of the normal function with:
double normal(double x, double sigma, double mu)
{
double func = 1.0/(sigma * sqrt(2.0*M_PI));
double t = (x-mu)/sigma;
return func * exp(-t*t/2);
}
#define _CRT_SECURE_NO_WARNINGS
#define _USE_MATH_DEFINES
#ifndef M_PI
#define M_PI (3.14159265358979323846)
#endif
#include<math.h>
#include<stdio.h>
#include <stdlib.h>
double normal(double x, double sigma, double mu)
{
double func = 1.0/(sigma * sqrt(2.0*M_PI));
double t = (x-mu)/sigma;
return func * exp((-0.5*t)* t);
}
I Finally got this code above working after tweaking with it literally all day lol, C math can be rather tricky, thank you for the help above as well.
Related
Im stuck maybe someone here can help me plzzz :)
I did wrong program that calc from radian to degri
I need to build a program like you calc Sin(x) in radian mode in calculator
I put radian x like 1 in radian and it need to give me in radian mode the calc of sin(1)
Like if i put sin(1) it need to give me 0.8414
and i cant use sin() and all this only standart and need to use taylor to calc.
help plz :) :')
my wrong code:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
double my_sin(double x);
/*my_sin func calc sin(x) from the main*/
double my_sin(double x){
double min_num = 0.000001;
double radian = x*(3.14/180);
double sol = radian;
int i;
int sign = 1;
int n;
int aseret = 1;
//Calc the solution if i <= 0.000001 it stop calc.
for(i=3;i <= min_num; i = i+2){
n = n * radian * radian;
sign = -(sign); //change the sign every round.
aseret = aseret * i * (i-1); //!3 = 3*2*1.
sol = sol + (pow(x,i)/aseret) *sign; // calc the solution.
}
return sol;
}
/*main func*/
int main()
{
double x = 0;
double result;
printf("please enter the number to check the SIN of it:");
scanf("%lf",&x);
result = my_sin(x);
printf("SIN(%f) = %f\n",x,result);
return 0;
}
Your main problem is that you are comparing the index i with the minimum value of the term. One consequence is that the loop stops immediately. It is the term x^i/i(i-1) which must be compared with the minimum value. As the series is alternating, the error at the end is lower than this minimum value.
It is also useles to perform the conversion to radian, as it seems you are entering a radian value.
Moreover, it is useless and inefficient to use pow() function to calculate x^i. Better to alculate this term iteratively.
Output:
please enter the number to check the SIN of it: 1
SIN(1.000000) = 0.841471
error = -1.59828e-010
Code:
#include <stdio.h>
#include <math.h>
double my_sin(double x){
double min_num = 0.000001;
int sign = 1;
double term = x;
double sol = term;
double x2 = x*x;
int i = 1;
//Calc the solution if term <= 0.000001 it stop calc.
do {
i += 2;
term *= x2 / (i * (i-1));
sign = -sign; //change the sign every round.
sol += term * sign;
} while (term > min_num);
return sol;
}
int main() {
double x;
printf("please enter the number to check the SIN of it: ");
scanf("%lf", &x);
double result = my_sin(x);
printf("SIN(%f) = %f\n", x, result);
double result_exact = sin(x);
double delta = result - result_exact;
printf ("error = %g\n", delta);
return 0;
}
You convert x to radians when it is already in radians.
Your loop condition is wrong, the loop terminates immediately and compares an integer with a double.
The variable n is uninitialised and the result of the expression it is used in is unused in any case.
Unnecessary headers included.
Change as per <<<<<< comments:
#include <stdio.h>
// #include <string.h> // <<<<<<<<<<<<<< REDUNDANT
// #include <ctype.h> // <<<<<<<<<<<<<< REDUNDANT
#include <math.h>
#define LIMIT 10 // <<<<<<<<<<<<<< ADD
double my_sin( double x );
/*my_sin func calc sin(x) from the main*/
double my_sin( double x )
{
// double min_num = 0.000001; // <<<<<<<<<<<<<< REMOVE
// double radian = x*(3.14/180); // <<<<<<<<<<<<<< REMOVE
double sol = x ; // <<<<<<<<<<<<<< CHANGE
// int i; // <<<<<<<<<<<<<< REMOVE
int sign = 1;
// int n = 0 ; // <<<<<<<<<<<<<< REMOVE - NOT USED
int aseret = 1;
//Calc the solution if i <= LIMIT it stop calc. // <<<<<<<<<<<<<< CHANGE
for( int i = 3; i <= LIMIT; i += 2 ) // <<<<<<<<<<<<<< CHANGE
{
// n = n * x * x; // <<<<<<<<<<<<<< REMOVE - RESULT NOT USED
sign = -(sign); //change the sign every round.
aseret = aseret * i * (i - 1); //!3 = 3*2*1.
sol = sol + (pow( x, i ) / aseret) * sign; // calc the solution.
}
return sol;
}
What is not working:
In the code below, the values input in scanf under getPositiveValue will not return. They return as 0 no matter what the input is.
I have no clue how to get around this. Can someone show me why it is not working?
What I have tried:
I tried using return CHAN; and even return CHAN.n; and all the other members but that did not work.
My code:
#include <stdio.h>
#include <math.h>
#define TRUE 1
#define FALSE 0
#define N 25 //number of lines
typedef struct CHANNEL_ //Structure CHANNEL
{
char name[9];
double n;//roughness coefficient
double S;//channel slope
double B;//width
double D;//maxDepth
} CHANNEL;
double computeVelocity(CHANNEL, double);
int main(void)
{
CHANNEL CHAN;
void getPositiveValue(CHANNEL);
void displayTable(CHANNEL);
//Function declarations
printf("Enter the name of the channel: ");
fgets(CHAN.name, 9, stdin);
getPositiveValue(CHAN);
printf("Channel data for %s\n Coefficient of roughness: %lf\n Slope: %lf\n Width: %lf\n Maximum depth: %lf\n", CHAN.name, CHAN.n, CHAN.S, CHAN.B, CHAN.D);
printf("Depth Average Velocity\n");
displayTable(CHAN); //function call to display the table with values
}
void getPositiveValue(CHANNEL CHAN)
{
int Flag; //sentinel
do
{
Flag = FALSE;
printf("Give the coefficient for roughness, slope, width, and maxdepth: ");
scanf("%lf %lf %lf %lf", &CHAN.n, &CHAN.S, &CHAN.B, &CHAN.D);
if(CHAN.n < 0 || CHAN.S < 0 || CHAN.B < 0 || CHAN.D < 0) //sentinel checkpoint
{
Flag = TRUE;
printf("The values must be positive.\n");
}
} while(Flag == TRUE);
}
void displayTable(CHANNEL CHAN)
{
double increment = CHAN.D/N;
double H = 0; //depth
double arraydepth[N]; //N is used to avoid magic numbers when defining array size
double arrayvelocity[N]; //N is used to avoid magic numbers when defining array size
int i; //using separate integers for the two different arrays just so it looks better and less confusing
for ( i = 0; i < N; i++)
{
H += increment;
arrayvelocity[i] = computeVelocity(CHAN, H);
arraydepth[i] = H;
printf("%lf %lf\n", arraydepth[i], arrayvelocity[i]);
}
}
double computeVelocity(CHANNEL CHAN, double H)
{
double U;
U = CHAN.B / H;
U = U / (CHAN.B + (2 * H));
U = pow(U, (2 / 3));
U = U / CHAN.n;
U = U * (sqrt(CHAN.S));
return U;
}
The input problem you are having is because of the fact that functions are call by value in C. This means that when you pass a struct to a function, it is a copy of the struct that is worked with in the function, not the original. Any changes made to the struct within the getPositiveValue() function are not visible once control returns to main().
To fix this problem, pass a pointer to the structure. Use the -> operator to dereference the pointer and access members in one shot. Here is a modified version of your code. I also took the liberty of moving your function declarations to the top of the program.
There is also an error in the call to the pow() function found in computeVelocity():
U = pow(U, (2 / 3));
should be:
U = pow(U, (2.0 / 3.0));
The expression 2 / 3 performs integer division, with the result zero, so after this call to pow(), U is always 1. This can be easily fixed by forcing floating point division, as in the second line above.
#include <stdio.h>
#include <math.h>
#define TRUE 1
#define FALSE 0
#define N 25 //number of lines
typedef struct CHANNEL_ //Structure CHANNEL
{
char name[9];
double n;//roughness coefficient
double S;//channel slope
double B;//width
double D;//maxDepth
} CHANNEL;
double computeVelocity(CHANNEL, double);
void getPositiveValue(CHANNEL *);
void displayTable(CHANNEL);
int main(void)
{
CHANNEL CHAN;
printf("Enter the name of the channel: ");
fgets(CHAN.name, 9, stdin);
getPositiveValue(&CHAN);
printf("Channel data for %s\n Coefficient of roughness: %lf\n Slope: %lf\n Width: %lf\n Maximum depth: %lf\n", CHAN.name, CHAN.n, CHAN.S, CHAN.B, CHAN.D);
printf("Depth Average Velocity\n");
displayTable(CHAN); //function call to display the table with values
}
void getPositiveValue(CHANNEL *CHAN)
{
int Flag; //sentinel
do
{
Flag = FALSE;
printf("Give the coefficient for roughness, slope, width, and maxdepth: ");
scanf("%lf %lf %lf %lf", &CHAN->n, &CHAN->S, &CHAN->B, &CHAN->D);
if(CHAN->n < 0 || CHAN->S < 0 || CHAN->B < 0 || CHAN->D < 0) //sentinel checkpoint
{
Flag = TRUE;
printf("The values must be positive.\n");
}
}while(Flag == TRUE);
}
void displayTable(CHANNEL CHAN)
{
double increment = CHAN.D/N;
double H = 0; //depth
double arraydepth[N]; //N is used to avoid magic numbers when defining array size
double arrayvelocity[N]; //N is used to avoid magic numbers when defining array size
int i; //using separate integers for the two different arrays just so it looks better and less confusing
for ( i = 0; i < N; i++)
{
H += increment;
arrayvelocity[i] = computeVelocity(CHAN, H);
arraydepth[i] = H;
printf("%lf %lf\n", arraydepth[i], arrayvelocity[i]);
}
}
double computeVelocity(CHANNEL CHAN, double H)
{
double U;
U = CHAN.B / H;
U = U / (CHAN.B + (2 * H));
U = pow(U, (2.0 / 3.0));
U = U / CHAN.n;
U = U * (sqrt(CHAN.S));
return U;
}
Sample program interaction:
Enter the name of the channel: chan
Give the coefficient for roughness, slope, width, and maxdepth: 0.035 0.0001 10 4.2
Channel data for chan
Coefficient of roughness: 0.035000
Slope: 0.000100
Width: 10.000000
Maximum depth: 4.200000
Depth Average Velocity
0.168000 0.917961
0.336000 0.566077
0.504000 0.423161
0.672000 0.342380
0.840000 0.289368
1.008000 0.251450
1.176000 0.222759
1.344000 0.200172
1.512000 0.181859
1.680000 0.166669
1.848000 0.153840
2.016000 0.142843
2.184000 0.133301
2.352000 0.124935
2.520000 0.117535
2.688000 0.110939
2.856000 0.105020
3.024000 0.099677
3.192000 0.094829
3.360000 0.090410
3.528000 0.086363
3.696000 0.082644
3.864000 0.079214
4.032000 0.076040
4.200000 0.073095
There are many compiler error in your code. Here is my first try to fix it
#include <stdio.h>
#include <math.h>
#define TRUE 1
#define FALSE 0
#define N 25 //number of lines
typedef struct CHANNEL_ {
char name[50];
double n;//roughness coefficient
double S;//channel slope
double B;//width
double D;//maxDepth
} CHANNEL;
double computeVelocity(CHANNEL, double);
void getPositiveValue(CHANNEL);
void displayTable(CHANNEL);
int main(void) {
CHANNEL CHAN;
printf("Enter the name of the channel: ");
fgets(CHAN.name, 50, stdin);
getPositiveValue(CHAN);
printf("Channel data for %s\n Coefficient of roughness: %lf\n Slope: %lf\n Width: %lf\n Maximum depth: %lf\n", CHAN.name, CHAN.n, CHAN.S, CHAN.B, CHAN.D);
printf("Depth Average Velocity\n");
displayTable(CHAN); //function call to display the table with values
}
void getPositiveValue(CHANNEL CHAN) {
int Flag; //sentinel
do {
Flag = FALSE;
printf("Give the coefficient for roughness: \n Give the slope: \n Give the channel width: \n Give the maximum depth of the channel: ");
scanf("%lf %lf %lf %lf", &CHAN.n, &CHAN.S, &CHAN.B, &CHAN.D);
if(CHAN.n < 0 || CHAN.S < 0 || CHAN.B < 0 || CHAN.D < 0) {
Flag = TRUE;
printf("The values must be positive.\n");
}
} while(Flag == TRUE);
}
void displayTable(CHANNEL CHAN) {
double increment = CHAN.D/N;
double H = 0; //depth
double arraydepth[N];
double arrayvelocity[N];
int i;
for ( i = 0; i < N; i++) {
H += increment;
arrayvelocity[i] = computeVelocity(CHAN, H);
arraydepth[i] = H;
printf("%lf %lf\n", arraydepth[i], arrayvelocity[i]);
}
}
double computeVelocity(CHANNEL CHAN, double H)
{
double U;
U = CHAN.B / H;
U = U / (CHAN.B + (2 * H));
U = pow(U, (2 / 3));
U = U / CHAN.n;
U = U * (sqrt(CHAN.S));
return U;
}
The first error would be struct definition. In C, you can define the struct and at the same time define a variable. But you should not use the same name to confuse yourself and the compiler. Also you need to understand void function does not return a value and cannot be on the right side of an = expression.
Use typedef can save you to type struct keyword each time you need it. You also need to use %s to output a string. Also typos here and there.
#include <stdio.h>
#include <conio.h>
#include <math.h>
#define ESP 0.0001
#define F(x) x^3-2.5x^2-1.8x+2.356
void main()
{
float x0,x1,x2,f1,f2,f0;
int count=0;
do
{
printf("\nEnter the value of x0: ");
scanf("%f",&x0);
}while(F(x0) > 0);
do
{
printf("\nEnter the value of x1: ");
scanf("%f",&x1);
}while(F(x1) < 0);
printf("\n__________________________________________________________\n");
printf("\n x0\t x1\t x2\t f0\t f1\t f2");
printf("\n__________________________________________________________\n");
do
{
f0=F(x0);
f1=F(x1);
x2=x0-((f0*(x1-x0))/(f1-f0));
f2=F(x2);
printf("\n%f %f %f %f %f %f",x0,x1,x2,f0,f1,f2);
if(f0*f2<0)
{
x1=x2;
}
else
{
x0 = x2;
}
}while(fabs(f2)>ESP);
printf("\n__________________________________________________________\n");
printf("\n\nApp.root = %f",x2);
getch();
}
The program can't seem to read the #define F(x) x^3-2.5x^2-1.8x+2.356 as function but when I use #define F(x) 3*(x) - 1 - cos(x) there's no error.
I tried #define F(x) (x)^3-2.5(x)^2-1.8(x)+2.356, no luck.
F(x) x^3-2.5x^2-1.8x+2.356
^ is not the power operator in C use pow(), powf() function (but in this case there is no need of it)
2.5x has to be 2.5 * x - buy a book about C
do not #define functions make them "real"functions
Do not use double literals in float expressions
float F(float x)
{
return x * x * x + 2.5f * x * x + 1.8f * x + 2.356f;
}
So I have to make this formula "y = y / (3/17) - z + x / (a % 2) + PI" in C
I am having a problem with (a%2) as it is returning odd values. ie 1%2 = 0.000001
int assignment7()
{
#define PI 3.14
int a=0,amod2;
double Ny=0,y=0,z=0,x=0;
printf("Enter values for x,y,z and a: ");
scanf("%d%lf%lf%lf",&a,&y,&z,&x);
//printf("%d,%lf,%lf,%lf\n",a,y,z,x);
//amod2=1%2;
//printf("%lf",amod2);
Ny=y/(double)(3/17) - z+x / amod2 + PI;
printf("%lf\n",Ny);
When you say:
printf("%lf",amod2);
the compiler expects amod2 to be a "long float" (aka a double), but you defined it as:
int amod2;
Also your prompt says "x,y,z and a" but you read in the order "a,y,z,x":
printf("Enter values for x,y,z and a: ");
scanf("%d%lf%lf%lf",&a,&y,&z,&x);
that's awkward at best.
EDIT: cleaned up a bit and made some assumptions about order of operations:
#include <stdio.h>
#define PI 3.14
#define DIVSOR (3.0/17.0)
int assignment7 ( void );
int assignment7 ( void ) {
double x = 0.0;
double y = 0.0;
double z = 0.0;
int a = 0;
int amod2;
double Ny;
printf("Enter values for x,y,z and a: ");
scanf("%lf%lf%lf%d",&x,&y,&z,&a);
amod2 = a % 2;
Ny = (y / DIVSOR) - z + (x / amod2) + PI;
printf("%lf\n", Ny);
return 0;
}
int main ( void ) { return assignment7(); }
You don't say what inputs you are giving it, (a test case with inputs and the expected results would be super helpful), but I can point out that x / (a % 2) is going to be infinity when a is 2 or 4 or 6 or ...
I'm designing an algorithm to define a simple method able to find the local maximum of a function f (x) given in an interval [a, b]
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define PI 3.141592653
float funtion_(float a, float x){
float result=0;
result = a * (sin (PI*x));
return result;
}
int main (){
double A = 4.875; //average of the digits of the identification card
double a = 0.0, b =1.0; //maximum and minimum values of the interval [a, b]
double h=0;
double N;
double Max, x;
double sin_;
double inf;
printf ("input the minux value: ");
scanf ("%lf", &inf);
printf ("input the N value: ");
scanf ("%lf", &N);
h= (b-a)/N;
printf("h = %lf\n", h);
x=a-h;
Max = -inf;
do {
x = x+h;
sin_ = funtion_(A, x);
if (sin_>=Max){
Max = sin_;
}
}while (x==b);
printf ("Maximum value: %lf.5", Max);
return 0;
}
The algorithm implements the function f (x) = A * sin (pi * x), where A is the average of the digits of my ID, and inf variable is assigned a number sufficiently greater than the values reached by the function in the interval [a, b] = [0.1].
The algorithm must find the local maximum of the function but it is the maximum returns always zero. do not understand why. What problem may be the logic of my solution?, this problem can be solved by this simple algorithm or some optimization by backtracking is necessary ? Thanks for your responses.
Several problems with this code; probably the most glaring is:
int a = 0, b = 1;
float Max, x;
/* ... */
do {
/* ... */
} while (x == b);
You cannot compare an int and a float for equality. It might work once in a great while due to dumb luck :) but you cannot expect this code to function reliably.
I strongly recommend changing all your int variables to double, all your float variables to double, and all the scanf(3) and printf(3) calls to match. While you can combine different primitive number types in one program, and even in one expression or statement, subtle differences in execution will take you hours to discover.
Furthermore, comparing floating point formats for equality is almost never a good idea. Instead, compare the difference between two numbers to a epsilon value:
if (fabs(a-b) < 0.001)
/* consider them equal */
You might want to scale your epsilon so that it matches the scale of your problem; since float really only supports about seven digits of precision, this comparison wouldn't work well:
if (fabsf(123456789 - 123456789.1) < 0.5)
/* oops! fabsf(3) used to force float */
/* and float can't tell the difference */
You might want to find a good introduction to numerical analysis. (Incidentally, one of my favorite classes back in school. :)
update
The core of the problem is your while(x == b). I fixed that and a few smaller problems, and this code seems to work:
#include
#include
#include
#define PI 3.141592653
float funtion_(float a, float x)
{
float result = 0;
result = a * (sin(PI * x));
return result;
}
int main()
{
float A = 4.875; //average of the digits of the identification card
float a = 0.0, b = 1.0; //maximum and minimum values of the interval [a, b]
float h = 0;
float N;
float Max, x;
float sin_;
float inf;
printf("\ninput the inf value: ");
scanf("%f", &inf);
printf("\ninput the N value: ");
scanf("%f", &N);
h = (b - a) / N;
x = a - h;
Max = -inf;
do {
x = x + h;
sin_ = funtion_(A, x);
if (sin_ >= Max) {
Max = sin_;
printf("\n new Max: %f found at A: %f x: %f\n", Max, A, x);
}
} while (x < b);
printf("Maximum value: %.5f\n", Max);
return 0;
}
Running this program with some small inputs:
$ ./localmax
input the inf value: 1
input the N value: 10
new Max: 0.000000 found at A: 4.875000 x: 0.000000
new Max: 1.506458 found at A: 4.875000 x: 0.100000
new Max: 2.865453 found at A: 4.875000 x: 0.200000
new Max: 3.943958 found at A: 4.875000 x: 0.300000
new Max: 4.636401 found at A: 4.875000 x: 0.400000
new Max: 4.875000 found at A: 4.875000 x: 0.500000
Maximum value: 4.87500
$
You are doing your calculations, in particular the initialisation of h, with integer arithmetic. So in the statement:
h = (b-a) / N;
a, b, and N are all integers so the expression is evaluated as an integer expression, and then converted to a float for assignment to h. You will probably find that the value of h is zero. Try adding the following line after the calculation of h:
printf("h = %f\n", h);
After you've fixed that by doing the calculations with floating point, you need to fix your while loop. The condition x = b is definitely not what you want (I noticed it was originally x == b before your formatting edit, but that's not right either).
Should the while condition be: while(x <= b)
while (x = b);
There is no way to exit the loop. b is always 1.