finding cube root in C++?

后端 未结 12 627
自闭症患者
自闭症患者 2020-12-03 15:18

Strange things happen when i try to find the cube root of a number.

The following code returns me undefined. In cmd : -1.#IND

cout<

        
12条回答
  •  温柔的废话
    2020-12-03 15:52

    If you ever have no math library you can use this way to compute the cubic root:

    cubic root

    double curt(double x) {
      if (x == 0) {
        // would otherwise return something like 4.257959840008151e-109
        return 0;
      }
      double b = 1; // use any value except 0
      double last_b_1 = 0;
      double last_b_2 = 0;
      while (last_b_1 != b && last_b_2 != b) {
        last_b_1 = b;
        // use (2 * b + x / b / b) / 3 for small numbers, as suggested by  willywonka_dailyblah
        b = (b + x / b / b) / 2;
        last_b_2 = b;
        // use (2 * b + x / b / b) / 3 for small numbers, as suggested by  willywonka_dailyblah
        b = (b + x / b / b) / 2;
      }
      return b;
    }
    

    It is derives from the sqrt algorithm below. The idea is that b and x / b / b bigger and smaller from the cubic root of x. So, the average of both lies closer to the cubic root of x.

    Square Root And Cubic Root (in Python)

    def sqrt_2(a):
        if a == 0:
            return 0
        b = 1
        last_b = 0
        while last_b != b:
            last_b = b
            b = (b + a / b) / 2
        return b
    
    def curt_2(a):
        if a == 0:
            return 0
        b = a
        last_b_1 = 0;
        last_b_2 = 0;
        while (last_b_1 != b and last_b_2 != b):
            last_b_1 = b;
            b = (b + a / b / b) / 2;
            last_b_2 = b;
            b = (b + a / b / b) / 2;
        return b
    

    In contrast to the square root, last_b_1 and last_b_2 are required in the cubic root because b flickers. You can modify these algorithms to compute the fourth root, fifth root and so on.

    Thanks to my math teacher Herr Brenner in 11th grade who told me this algorithm for sqrt.

    Performance

    I tested it on an Arduino with 16mhz clock frequency:

    • 0.3525ms for yourPow
    • 0.3853ms for nth-root
    • 2.3426ms for curt

提交回复
热议问题