[Solved] How to make math logarithm functions in C99?


Q: How do I fix problem 1 … ?

10 ^ i is 10 exclusive-or’ed with i. It is not 10i.

To find the integer portion of log10(num)

int i_portion = 0;
if (num <= 0) Handle_elsewhere();
else {
  int i_portion = 0;
  int n = num;
  while (n >= 10) {
    n /= 10;
    i_portion++;
  } 
  printf("%d\n", i_portion);
} 

Q: … and how do I make the function work as how I explained in problem 2?

Below is a quick solution since C99:

#include <math.h>
float log_num(int num) {
  return log10f(num);
}

To code without <math.h> is fairly broad. For efficient construction, we need design parameters.

First, be clear about base. The standard log() is base e, not base 10 as the question
implies.

Corner/Error handling: How do you want to handle negative inputs? Logany positive base(0) is usually returned as -∞. For finite positive values, no range issues. What should be returned for +∞, perhaps +∞? What should be returned for NaN, perhaps NaN?

Accuracy/precision: Do you want the best result or willing to given up accuracy for speed or small code foot-print? Why return float versus the more common double?

Performance: simply code that is of poor run-time performance OK? Just code per Logarithm Calculation. Since the goal includes my_log_i(int), my_log_f(float), my_log_d(double), for now, just code my_log_d(double) and have the the others call it.

Portability – how portable?


Sure we can code up a simply float my_log_10(int), but without the design details, the result would be lacking in many ways.

solved How to make math logarithm functions in C99?