I'm trying to learn how to calculate the logarithm base 10 of any numbers that I enter via scanf to my code. I figure that I could calculate the ln(a) a being the number input. I have a working code that calculates this; however now i just want to divide any numbers that my ln(a) code outputs by the defined LN10. This is because the natural log of a number divided by the natural log of 10 will output my required log base 10 value that I am working to achieve. Here is the mess I have at the moment. Any help is extremely appreciated!
#define _CRT_SECURE_NO_WARNINGS
#define ALMOSTZERO 0.0000000000000000001
#define LN10 2.3025850929940456840179914546844
#include <stdio.h>
double log10(double);
double ln(double);
void main()
{
{
double x, a;
printf("Enter value: ");
scanf("%lf", &x);
while (x > 0)
{
double log10 = ln(x) * LN10;
printf("log10(%lf)=%lf\n", x, a);
printf("Enter value: ");
scanf("%lf", &x);
}
}
}
double ln(double x)
{
double sum = 0.0;
double xmlxpl = (x - 1) / (x + 1);
double denom = 1.0;
double frac = xmlxpl;
double term = frac / denom;
while (term > ALMOSTZERO)
{
sum += term;
//generate next term
denom += 2.0;
frac = frac * xmlxpl * xmlxpl;
term = frac / denom;
}
return 2.0 * sum;
}
There are some issues in your code, but what you need to calculate the log10 having written the function to calculate the ln of a number is just another simple function:
#define LN10 2.3025850929940456840179914546844
double log10( double x ) {
return ln(x) / LN10;
}
I'd change your ln
function too, at least the condition to stop the iterations, becuase term
can become little enough that sum == sum + term
(numerically speaking).
In your actual code you can stop earlier, checking that abs(term)
be less then some epsilon relative to the value of sum
. I simply used this:
double ln(double x)
{
double old_sum = 0.0;
double xmlxpl = (x - 1) / (x + 1);
double xmlxpl_2 = xmlxpl * xmlxpl;
double denom = 1.0;
double frac = xmlxpl;
double term = frac; // denom start from 1.0
double sum = term;
while ( sum != old_sum )
{
old_sum = sum;
denom += 2.0;
frac *= xmlxpl_2;
sum += frac / denom;
}
return 2.0 * sum;
}
This will save you some iterations giving the same (approximated) result of your code. To take care of the last terms you should adopt some other numeric strategy.
Your main needs some changes too. At least more control of the user input:
#include <stdio.h>
double log10(double);
double ln(double);
int main()
{
double x, a;
printf("This program calculates the logarithm base 10.\n");
printf("Enter a positive value: ");
while ( 1 == scanf("%lf", &x) && x > 0.0)
{
double a = log10(x);
printf("log10(%lf) = %.12lf\n", x, a);
printf("Enter a positive value: ");
}
return 0;
}