![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
#1 |
|
Newbie
Join Date: Jan 2006
Location: London, Ontario, Canada
Posts: 16
Rep Power: 0
![]() |
Math functions
Hi everyone,
I have a problem regarding certain math functions in C/C++. I am trying to use the sqrt() function in my program, but I get compilation errors, stating that the library has not been included. I have include them in the program header. Also is there a way to raise a variable to a power such as x^2 where the (^) notation is used often in Maple or Mathematica does not seem to work in C/C++. #include <stdio.h>
#include <stdlib.h>
#include <math.h>
main() {
double x, func = 0.0, func2 = 0.0, resultF, errorF, resultErr;
int try, ntry;
printf("Input the number of MC trials\n");
scanf("%d",&ntry);
srand((unsigned)time((long *)0));
for (try=0; try<ntry; try++) {
x = rand()/(float)RAND_MAX;
func = func + x*x; /* function to be evaluated is parabola of x^2 */
func2 = func2 + x*x*x*x;
errorF = sqrt(func - func2);
}
resultF = func/ntry;
resultErr = errorF/ntry;
printf("MC estimate for function = %f\n", resultF);
printf("MC error for function = %f\n", resultErr);
}I am using Debian Linux system with GNU C/C++ compiler. Thank you for your help. Really appreciate it. |
|
|
|
|
|
#2 |
|
Resident Grouch
![]() ![]() ![]() ![]() ![]() ![]() Join Date: Jun 2005
Posts: 6,453
Rep Power: 10
![]() |
You should post your exact error message. The presence of headers and libraries is NOT the same thing. Investigate the POW function; the '^' is a bitwise exclusive-or operator in C.
__________________
Abstraction doesn't make it impossible to write bad code; it makes it possible to write superior code. Contributor's Corner: Grumpy on C++ Exceptions DaWei on Pointers |
|
|
|
|
|
#3 |
|
Programming Guru
![]() ![]() ![]() |
Be careful in your variable names... in some languages "try" is a keyword used in exception handling. Yes, Pow is the exponent function and we will need to see the exact error msg.
__________________
http://jasonpowers.net "There are a thousand hacking at the branches of evil to one who is striking at the root." |
|
|
|
|
|
#4 |
|
Expert Programmer
Join Date: Sep 2004
Location: Ontario, Canada
Posts: 555
Rep Power: 5
![]() |
Did you remember to link the Math library with -lm ?
gcc foo.c -o foo -lm
__________________
Johnny was a chemist's son but Johnny is no more, for what Johnny thought was H2O was H2SO4 |
|
|
|
|
|
#5 | |
|
Newbie
Join Date: Jan 2006
Location: London, Ontario, Canada
Posts: 16
Rep Power: 0
![]() |
Quote:
It worked like a charm. |
|
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|