I would apprecite a little help. I need to create simple application counting definite integral in quadrature rule, which is given as a parameter when running. I started with adding parametres, but when I use brackets in it, compiler won't compile my application. And then I am stuck in getting started, how to trasnfer parameter as a integral to some computing part?
Thanks
edit:
int x;
int i;
float sum=0;
double PI;
printf("Please enter the parts to divide the interval: ");
scanf("%d", &x);
for (i=1; i<x; i+=2){
if (i%4==1)
sum=sum+1./(double)i;
else
sum=sum-1./(double)i;
}
PI= 4*sum;
printf("The sum is %f\n", sum);
printf("Approximate value of PI is %f\n", PI);
It's hard to know what you're asking here.
Are you trying to do Gaussian or some other type of quadrature scheme with differing orders?
Are you having problems figuring out how to pass a function pointer to be evaluated by the numerical integration function?
When you say you have a compiler error, it suggests that you haven't even gotten to the point where you can tell whether your implementation works or not. How well do you know C? You should read and digest the error message and go back to a language reference to see where you went wrong until all the compiler errors are gone.
Once you achieve that, the fun begins: now you have to worrk about whether or not your code actually works.
UPDATE: I don't see any quadrature in the code you posted. Looks like a simple Euler or Simpson's rule.
I'd recommend something like "Numerical Recipes":
http://eiffel.ps.uci.edu/cyu/p231C/LectureNotes/lecture10:integration/lecture10.pdf
Related
I'm writing a program to track the number of rectangles being made in one week using the exponential growth function (X = a(1+b)^t). One person can make 60 rectangles per day.
a represents the initial population, this is the number of people already making rectangles on the first of the week. b represents the growth rate, this is the number of new people making rectangles each day. t represents the time interval, which is 7 days for this program.
I'm having difficulties getting started with the problem, and I need some guidance please.
I was thinking using using math.h and pow, something like this (this code is not compiling)
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
int main() {
int initial_POPULATION;
int time_INTERVAL;
double growth_RATE;
printf("How many people are making rectangles at the
biginning of the week?\n");
scanf("%d", &initial_POPULATION);
printf("How many people are making rectangles each day?
\n");
scanf("%1f", &growth_RATE);
//Exponential growth function X = a(1+b)^t
printf("%d rectangles will be made this week!\n",
initial_POPULATION(pow(1+growth_RATE),time_INTERVAL));
return 0;
}
There are a couple problems, but the most apparent is that you are not setting the value of time_INTERVAL anywhere. Next is the line where the final value is calculated: in C, you need to use * to denote multiplication. Parens do not work as implied multiplication operators like in regular math (at any rate, the way the parenthesis are being used in the last printf is not right). Finally, make sure to read growth_RATE as a double by using %lf as the format specifier in scanf (using %f reads it as a single precision 4-byte value, even though it's declared as a double which is... well, double that).
Try this:
scanf("%lf", &growth_RATE);
time_INTERVAL=7;
printf("%f rectangles will be made this week!\n", initial_POPULATION * pow(1+growth_RATE, time_INTERVAL));
Also, as mentioned by #Asadefa, remove the line breaks from the string literals.
There are 4 possible reasons your code isn't compiling.
Did you try compiling like this if you're using unix, with -lm?
gcc /path/to/file.c -lm -o /path/to/outputfile
Also, you cannot have line breaks in string literals. This isn't allowed:
char *MyString = "Hello
World";
On top of that, you are trying to call initial_POPULATION (int) as if it were a function:
initial_POPULATION(pow(1+growth_RATE),time_INTERVAL)
Maybe you meant:
initial_POPULATION*(pow(1+growth_RATE),time_INTERVAL)
And lastly, time_INTERVAL is uninitialized, as brought up by #Z4-tier.
I need to add two vectors in the arrays together. For example my code should execute the vector = {3,6,9}.
I dont really know what I did wrong as I am still new to coding. So any help is appreciated!
void add_vectors( double vector1[3]={1,2,3},double vector2[3]={1,2,3},double
vector3[3]={1,2,3}, int n)
{
n=sizeof(vector1);
int i;
for(i=0; i>n; i++)
{
scanf("%f", &vector1[i]);
scanf("%f", &vector2[i]);
vector3[i]=vector1[i]+vector2[i];
}
printf (vector3[]);
Sorry for the bad formatting but it's my frist time using this site.
There are several mistakes here in the code:
First, sizeof() gives you a size of something in a memory (in bytes), which is probably not what you desire.
Secondly, i>n statement means that the loops will execute only while i > n! The first time i = 0, and n is a positive integer. That means that the loop will be skipped, since i is not larger than n.
Third, printf() does not work like this.
I explained you the second point; my first and third points are widely explained on the internet: try finding these answers yourself.
I'm new to C language, it is required for my degree to complete one course on C programming. Hope the title makes sense... I had a hard time trying to convey what I meant. I'll elaborate here.
The problem I am facing right now is double type data being able to slip through the program undetected when it should have been rejected. This happens when a number very very close to the boundaries I set is provided.
In this assignment, in order to get an HD, my code has to have identical output to the lecturer's. The solutions are able to detect any number larger than the boundaries, no matter how close.
Basically, the program will ask the user to provide a GPA which is from 0 to 4.
I tried the following inputs:
4.01 rejected
4.001 rejected
...
4.000001 rejected
But at 4.0000001, it is accepted. This should not happen at all. I am baffled.
Here's my code:
double GPA=-1; /*Flags are being initialised*/
int GPAflag=1;
while(GPAflag){
char str[50];
char *ptr;
int isnum=1,n=0,i,point=0;
printf("Enter GPA>");
fflush(stdin);
gets(str);
n = strlen(str);
if(n==0){ /*string length is 0? There was no input, thus invalid*/
printf("Invalid GPA. ");
isnum=0;
}else{
for(i=0;i<n;i++) /*Validates numerical inputs, if not numerical, prompts user with error*/
if(!(str[i]>='0' && str[i]<='9')){
if(str[i]!='.'){
printf("Invalid GPA. ");
isnum=0;
break;
}else{
point++;
}
}
}
if(isnum){ /*If the input is a number, it may still be invalid*/
GPA=strtod(str, &ptr); /*The string is converted to a double*/
if(GPA>=0&&GPA<=4&&point<=1) /*If GPA is between 0 and 4, and the above is also satisfied (point=1), then the flag is 0 and thus a valid input*/
GPAflag=0;
else
printf("Invalid GPA. "); /*If not, it is still invalid*/
}
}
I personally don't think this will be a problem but I would really like to know why it happens, and if possible, a way to fix it.
I can simply make a FOR loop:
IF leading number is 4 and there's a '.'
-> Reject
But this seems like hard coding to me, I think it's rather a workaround than an actual solution.
Or I can change the IF statement from "<=4" to "<4.0000000000000000000000...1". Which in my opinion should lose marks... (if I was the marker I will take marks off for that)
Also, I am totally aware that the function "gets" is primitive and causes many problems (overflow... etc.). I have tried using fgets but it's a pain to implement... replacing the '\n' with '\0' blah blah... we haven't even learnt gets, let alone fgets. Is there a better way to implement fgets? Maybe have a function to replace the '\n'? I've tried that and it refused to work.
Any help and tips are greatly appreciated!
OP's true code was using float GPA=-1; and so GPA=strtod("4.0000001", &ptr); resulted in a GPA value of exactly 4.0 due to the greater limited precision of float versus a double.
By using double GPA;, as in the posted code, GPA=strtod("4.0000001", ... and GPA=strtod("4.000000001", ... will return a value just greater than 4. Even GPA=strtod("4.00000000000001", ... is likely to return a value a bit larger than 4.
At some point the limited precision of double will render GPA=strtod("4.0 many digits 001", ... as 4.0. A typical solution to limit the number of digits to something like 15 or less.
(Could taunt the user if more that 15 digits are used.)
The problem is solved, and looking back, it was due to a mistake:
In the structure, I have declared GPA as a float. I later changed it in my functions but missed out the most important part. As a result, the GPA was still stored as a float. Hope this conclusion is correct.
The limitations of the datatype causes round-off errors when an incredibly "close to allowed" value is provided.
Lesson learnt: When changing something, always make sure everything is consistent.
I appreciate all the help! Thanks a lot!
What is wrong with this code? I am learning both Python and C at the same time. Similar code on Python works fine but I am confused why this does not work here?
#include <stdio.h>
float a, b, c,min_value, max_value;
int main(){
printf("Enter a number here:");
scanf("%f",&a);
b=(max_value+min_value)/2;
while(abs(b*b-a)>0.1){
if (b*b>a){
max_value=b;
b=(max_value+min_value)/2;
}
else if(b*b<a){
min_value=a;
b=(max_value+min_value)/2;
}
printf("the square root of the number is %f",b);
}
}
In C, abs is an integer function - passing float values to it will result in truncation, so small values < +/-1.0 will just become 0. You need to use fabs for floating point values. Change:
while(abs(b*b-a)>0.1){
to:
while(fabs(b*b-a)>0.1){
and add:
#include <math.h>
near the top of your source file.
A lot of things are wrong:
float a, b, c,min_value, max_value;
You shouldn't declare these variables outside the main function.
b=(max_value+min_value)/2;
max_value and min_value are not defined, what are you expecting here?
if (b*b>a){
max_value=b;
b=(max_value+min_value)/2;
}
else if(b*b<a){
min_value=a;
b=(max_value+min_value)/2;
}
Once again, max_value and min_value may not be defined. I could continue.
If you are trying to implement a sqrt function, perhaps you should take a look at someone else's code, as it seems obvious you lack knowledge in C.
For future references, please state what your program is trying to accomplish and what errors are occuring. Not trying to be mean or condescending; just giving you a heads up on Stack Overflow policy on question phrasing.
That said, on a brief glance I did notice that you also did not define "max_value" or "min_value" before using them in line 6 (where you set a value to "b"). In addition, declaring your variables outside the main function makes them global variables, which I would suggest avoiding if your variables are not going to be used in another program (via "#include ").
I am extremely new to programming in general, so please forgive my noobishness. I am trying to scale down the res[?] array in the function below. I know the problem that the res[?]*(multiplier/100) is creating a decimal answer instead of the required format which is an integer therefore I need to convert the result before it is plugged into the res[?].
I did think of turning res[] array into a double but I wasnt sure whether the initwindow(?,?) was compatible with integer values.
I am on mingw with code blocks. the linker and compiler has customized setting made by my professor. I am on Plain\basic C???
I tried to apply the techniques this website used about the truncating conversion. But doesn't seem to work. http://www.cs.tut.fi/~jkorpela/round.html
Debugger watcher shows that res[?] is equivalent to 0.
#include <stdio.h>
#include <graphics_lib.h>
#include <math.h>
int res[2]//contains a array which contains the vertical and horizontal detected resolution from main()
void function(res)
{
printf("Please note the lowest resolution available is 800x600\n");
printf("Please enter percentage ratio % below 100:");
scanf("%d",&multiplier);
res[1]=(int)(res[1]*(multiplier/100));
res[2]=(int)(res[2]*(multiplier/100));
blah blah blah blah.............
initwindow(res[1],res[2]) //from custom header that my professor made which initializes basic graphics window
return;
}
I'm assuming multiplier is an int to match the %d format.
multiplier/100 is guaranteed to be zero (if the user follows directions and provides a number less than 100). You can do (res[x]*multiplier)/100 to make sure the multiply happens first (you're probably okay without the parentheses, but rather than think about order of operations why not be explicit?)
The cast to int is unnecessary, because an int divided by another int is always an int.
Unless your professor has done some very interesting things, you should also note that a two-element array such as res would have elements res[0] and res[1], not res[1] and res[2].
you don't need to cast in this situation because the conversion is done implicitly . you only need a cast to assign the content of a variable to a variable of different type .
Looks like the multiplier variable is an int, so the result of multiplier/100 expression will be 0 in all cases.
Also, it's a good programming practice to check the validity of user's input.
You must declare multiplier before you use it:
int multiplier;
printf("Please note the lowest resolution available is 800x600\n");
printf("Please enter percentage ratio % below 100:");
scanf("%d",&multiplier);
And the index is staring from 0 not 1. And you should initialize res[0] and res[1] before using them. So:
res[0] = 800;
res[1] = 600;
And the division of multiplier by 100 will truncate to 0, try this without casting as it will be automaticly converted:
res[1]=(multiplier*res[0])/100;
res[1]=(multiplier*res[1])/100;