Problems squaring # in C - rounding-error

I'm trying to compile a program in C to return the square of a number, for instance 1^2=1, but the program compiles without issues and always returns a value of 0.
What did I do wrong?
#include <stdio.h>
#include <math.h>
int main(int argc, const char * argv[])
{
/* Define temporary variables */
double value1, value2;
double result;
/* Assign the values we will use for the pow calculation */
value1 = 0;
value2 = 0;
/* Calculate the result of value1 raised to the power of value2 */
result = pow(value1, value2);
/* Display the result of the calculation */
printf("%f raised to the power of %f is %f\n", value1, value2, result);
return 0;
}

You can compute exponent or power with pow function:
#include <math.h>
double pow(double x, double y);

Its a simple error. You forgot to call the [mySquare setPowering]; function. Also you were passing some weird unused into to that function so i clipped it out.
Here's your fixed code. Though next time you should fine tooth comb your code before asking us. Otherwise, you won't learn important debugging skills. The best method for that is to just literally walk line by line and make sure everything is being used correctly... thats how i found the error :)
#import <Foundation/Foundation.h>
#import <math.h>
#interface Square: NSObject
{
int Constant;
int Power;
int Powering;
}
-(void) print;
-(void) setConstant: (int) c;
-(void) setPower: (int) p;
-(void) setPowering; // <-- HERE
#end
#implementation Square
-(void) print
{
NSLog (#"%i", Powering);
}
-(void) setConstant: (int) c
{
Constant = c;
}
-(void) setPower: (int) p
{
Power = p;
}
-(void) setPowering // <-- HERE
{
NSLog (#"%i^%i", Constant, Power); // This is optional
Powering = pow(Constant,Power);
}
#end
int main (int argc, const char * argv[])
{
Square *mySquare;
mySquare = [Square alloc];
mySquare = [mySquare init];
[mySquare setConstant: 2];
[mySquare setPower: 3];
[mySquare setPowering]; // <-- HERE
NSLog (#"The value of myPower is:");
[mySquare print];
return 0;
}

Based on your code:
[mySquare setConstant: 2];
[mySquare setPower: 3];
NSLog (#"The value of myPower is:");
[mySquare print];
I think you need to call [mySquare setPowering] for Powering be calculated.
[mySquare print] is new to me. This is trying to print the class? I think that's weird. I think you should print the mySquare.Powering to check the value. Try something like
NSLog("Powering: %d",mySquare.Powering);
Not sure why you are using INT for floating point calculations. That could affect your results too I think. best to use float for all variables.
That's all my comment.

Related

Calculating $\sqrt[3]{x}$ with Babylonian method

Consider my attempt to implement the Babylonian method in C:
int sqrt3(int x) {
double abs_err = 1.0;
double xold = x;
double xnew = 0;
while(abs_err > 1e-8) {
xnew = (2 * xold + x/(xold* xold))/3;
abs_err= xnew-xold;
if (abs_err < 0) abs_err = -abs_err;
xold=xnew;
}
return xnew;
}
int main() {
int a;
scanf("%d", &a);
printf(" Result is: %f",sqrt3(a));
return 0;
}
Result is for x=27: 0.0000?
Where is my mistake?
While the function returns an int, that value is printed with the wrong format specifier, %f instead of %d.
Change the signature (and the name, if I may) into something like this
double cube_root(double x) { ... }
Or change the format specifier, if you really want an int.
Following the explanation from tutorialspoint, which states, that the basic idea is to implement the Newton Raphson method for solving nonlinear equations, IMHO, the code below displays this fact more clearly. Since there is already an accepted answer, I add this answer just for future reference.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
double rootCube( double a)
{
double x = a;
double y = 1.0;
const double precision = 0.0000001;
while(fabs(x-y) > precision)
{
x = (x + y) / 2.0;
y = a / x / x;
}
return x;
}
int main(int argc, const char* argv[])
{
if(argc > 1)
{
double a =
strtod(argv[1],NULL);
printf("cubeRoot(%f) = %f\n", a, rootCube(a));
}
return 0;
}
Here, in contrast to the original code of the question, it is more obvious, that x and y are the bounds, which are being improved until a sufficiently accurate solution is found.
With modification of the line in the while block, where y is being updated, this code can also be used to solve similar equations. For finding the square root, for example, this line would look like this: y = a / x.

Why is my difference function not producing the actual difference and giving back zero?

So I am new to C and trying to prove Stirlings approximation. The natural_log and approximation function does work from what I have tested. And right now I am learning on how to parse those arrays into the difference function. I looked at over code online and it seems that I am using the syntax correctly but it doesn't give me the result I wanted.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define ELEMENTS 100
void natural_log ();
/* Obtain the natural log of 0 to 100 and then store each value in an array */
void approximation ();
/* Use the sterling approximation caluculate the numbers from 0 - 100 and then store it in an array */
double * difference ();
/* Calculate the difference between the arrays */
double * percentage ();
/* Calculate the percentage of the difference and return the array */
int main () {
natural_log ();
approximation ();
difference ();
return 0;
}
void natural_log () {
static double natural_array[ELEMENTS]; /* set up the array */
int i, j; /* set up the integer to increase the array by a value */
natural_array[0] = 0.0; /* set up the first value in the array */
natural_array[1] = log(1.0);
double x;
x = natural_array [1];
for (i = 2; i <=100; i++) { /* set up the for loop to increment the i */
natural_array[i] = x + log(1 + i);
x = natural_array[i];
/* printf ("Element[%d] = %f\n", i, x); Check */
}
}
void approximation () {
static double approximation_array[ELEMENTS]; /* set up the array */
int i; /* set up the integer to increase the array by a value */
for (i = 0; i <=100; i++) {
approximation_array[i] = (i) * log(i) - (i);
/* printf ("Elements[%d] = %f\n", i, approximation_array[i]); Check */
}
}
double * difference (double * natural_array, double * approximation_array) {
static double difference_array[ELEMENTS];
int i;
for (i = 0; i < 100; i++) {
difference_array[i] = (natural_array[i] - approximation_array[i]);
printf ("Elements[%d] = %f\n", i, difference_array[i]);
}
return difference_array;
}
So when I run the program it produces this output
Element[0] = 0.0000
Element[1] = 0.0000
Element[2] = 0.0000
....
....
Element[100] = 0.0000
I know there are differences in the natural log and the approximation when I ran the check lines for the print function but it doesn't seem to be getting those numbers any ideas?
Your code causes undefined behaviour by calling a function with the wrong number of arguments.
For example, double * difference (double * natural_array, double * approximation_array) must be called with two arguments. But you write:
difference();
in main. Normally compilers would diagnose this and print an error message, however you disabled that feature by writing the non-prototype declaration double * difference ();.
The first thing you should do is remove all of the non-prototype declarations. Either use prototypes (e.g. double * difference (double *, double *);), or place the function bodies in a different order so that no forward declaration is necessary.
Functions that take no arguments should have the parameter list (void) , not ().
After that you will need to re-design your function arguments and return values so that the arrays you need are available. For example, the natural_log() and approximation() functions work on arrays which are contained inside those functions and you never expose those arrays outside of the function. Instead you need to have difference work on those arrays.

Keeping geting a zero in the main function

I added a few printf stantments to see if the information is being computer and passed correctly, and while is is being computed correctly in the calcMean function, I keep getting zeros in the main function. I am not sure where my mistake is.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void calcMean(int [], int, float);
void calcVariance(int [], int, float);
int main(void)
{
/*create array and initialize it with values*/
int mainArr [ ] = {71,1899,272,1694,1697,296,722,12,2726,1899,
.......
1652,488,1123,17,290,1324,2495,1221,2361,1244,
813,2716,1808,2328,2840,1059,2382,2391,2453,1672,
1469,778,2639,357,2691,1113,2131,23,2535,1514,
2317,45,1465,1799,2642,557,1846,1824,1144,1468,-1};
/*create initilized values for variables*/
float mean = 0.0;
int counter = 0;
calcMean(mainArr, counter, mean);
calcVariance(mainArr, counter, mean);
printf ("Mean: %10.2f\n", mean); /*gives the average number to one decimal place*/
printf ("counter: %10.0d\n", counter);
getchar();
}/*End of the program*/
void calcMean(int mainArr[], int counter, float mean)/*This function finds the Mean(average) of the function, and the size of the array*/
{
int sentinel = -1;
float sum = 0.0;
int index = 0;
for (index; mainArr[index] != sentinel; index++) /*gets the total numbers in the function and the sum*/
{
counter++;
sum = sum + mainArr[index];
} /*end of the sumation and counting of integers*/
printf ("%0.0d\n", counter);
mean = ((float) sum / counter); /*Divides the sum by the total number of numbers to find the mean*/
printf ("mean: %10.2f\n", mean);
}
void calcVariance(int mainArr[], int counter, float mean)
{
int varindex = 0;
int numerator =0;
int square = 0;
int variance = 0;
int sumation = 0;
for(varindex; varindex<counter; varindex++)
{
numerator = (mainArr[varindex] - mean);
square = (numerator * numerator);
sumation = sumation + square;
variance = sumation / (counter-1);
}
printf ("variance %10.2f\n", variance);
}
You're assuming your function changes the value of outer variables. It won't.
calcMean(mainArr, counter, mean);
^ ^ pass by value
void calcMean(int mainArr[], int counter, float mean)
^ ^ receive by value
Modifying counter inside the function changes only the local variable.
Function parameters are copied into functions. So the variables inside a function will not change the parameters in the outer function.
You will need to do something like the following to any function which you wish to pass back more than one value from a function. (If you only need to pass back one value that can be returned with the function return statement).
// declare the parameters you wish to pass back to calling function as pointers
void calcMean(int [], *int, *float);
// pass the address of the variables:
calcMean(mainArr, &counter, &mean);
// obtain the values of the pointers in your calcMean using derefence operator *
printf ("%0.0d\n", *counter);
*mean = ((float) sum / *counter);
OP later requested an answer with little use of pointers.
As others (#suspectus, #Karoly Horvath, #Carl Norum) correctly pointed out the problem that passing into a function mean does not change it.
main() has an object named mean. That object's value was used to initialize the object called mean in the argument list of calcMean(). calcMean() proceeded to set its mean to some value. At the end of the function, the original mean in main() is not affected.
Instead, use the return value of function calcMean() to set mean in main().
// void calcMean(int mainArr[], int counter, float mean)
float calcMean(int mainArr[], int counter) {
float mean;
...
mean = ((float) sum / counter);
return mean;
}
int main(void) {
...
float mean = 0.0;
...
// calcMean(mainArr, counter, mean);
mean = calcMean(mainArr, counter);
...
}
Do the same for calcVariance
C is a pass-by-value language. Modifying mean and counter in the other functions doesn't affect their values in main().

Getting the fractional part of a double value in integer without losing precision

i want to convert the fractional part of a double value with precision upto 4 digits into integer. but when i do it, i lose precision. Is there any way so that i can get the precise value?
#include<stdio.h>
int main()
{
double number;
double fractional_part;
int output;
number = 1.1234;
fractional_part = number-(int)number;
fractional_part = fractional_part*10000.0;
printf("%lf\n",fractional_part);
output = (int)fractional_part;
printf("%d\n",output);
return 0;
}
i am expecting output to be 1234 but it gives 1233. please suggest a way so that i can get desired output. i want the solution in C language.
Assuming you want to get back a positive fraction even for negative values, I'd go with
(int)round(fabs(value - trunc(value)) * 1e4)
which should give you the expected result 1234.
If you do not round and just truncate the value
(int)(fabs(value - trunc(value)) * 1e4)
(which is essentially the same as your original code), you'll end up with the unexpected result 1233 as 1.1234 - 1.0 = 0.12339999999999995 in double precision.
Without using round(), you'll also get the expected result if you change the order of operations to
(int)(fabs(value * 1e4 - trunc(value) * 1e4))
If the integral part of value is large enough, floating-point inaccuracies will of course kick in again.
You can also use modf() instead of trunc() as David suggests, which is probably the best approach as far as floating point accuracy goes:
double dummy;
(int)round(fabs(modf(value, &dummy)) * 1e4)
number= 1.1234, whole=1, fraction=1234
int main()
{
double number;
int whole, fraction;
number = 1.1234;
whole= (int)number;
fraction =(int)(number*10000);
fraction = fraction-(whole *10000);
printf("%d\n",fraction);
printf("%d\n",whole);
return 0;
}
A solution for any number could be:
#include <cmath>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
float number = 123.46244;
float number_final;
float temp = number; // keep the number in a temporary variable
int temp2 = 1; // keep the length of the fractional part
while (fmod(temp, 10) !=0) // find the length of the fractional part
{
temp = temp*10;
temp2 *= 10;
}
temp /= 10; // in tins step our number is lile this xxxx0
temp2 /= 10;
number_final = fmod(temp, temp2);
cout<<number_final;
getch();
return 0;
}
Use modf and ceil
#include <stdio.h>
#include <math.h>
int main(void)
{
double param, fractpart, intpart;
int output;
param = 1.1234;
fractpart = modf(param , &intpart);
output = (int)(ceil(fractpart * 10000));
printf("%d\n", output);
return 0;
}

Storing a Randomly generated number in a variable

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;
}

Resources