Given a real number x! = 0. Calculate the fraction using the recursive subroutine:

formula

When calculating a fraction through recursion, even with double it counts only as a function y = x / x ^ 2. How to make the calculation more accurate, so that the part in which the recursion is also taken into account?

#include "stdafx.h" #include<iostream> #include<cmath> using namespace std; int func(float i, float x) { i*=2; if (i < 256) return ((x*x + i) / func(i, x)); else return((x*x + (i / x*x))); } int _tmain(int argc, _TCHAR* argv[]) { setlocale(LC_ALL, "RUS"); float x; cout << "Введите X"; cin >> x; float y; int i = 1; y = x/func(i,x); cout << "Ответ:" << y<<"\n"; system("pause"); return 0; } 
  • one
    x * x + i / func (i, x) - Igor
  • 2
    use a double, it will be better for calculations. - Alex.B
  • Even with doubles it counts only as a function of y = x / x ^ 2. How to make the calculation more accurate so that the part in which the recursion also influences the answer? - Clarence
  • Rotate the picture before loading - not? - Qwertiy
  • one
    Tip for the future: if you want the answer to be more accurate, you can try to “turn” the fraction and get it in the form of a classical rational fraction: y=(x^16+508*x^12+41664*x^8+634880*x^4+1048576)/(x*(x^16+510*x^12+42672*x^8+714240*x^4+2031616)) Next, read according to Horner’s scheme or by some other method minimizing the number of actions. Plus, get rid of recursion. - Zealint

2 answers 2

Do not abuse brackets

 double func(int i, double x) { i = i * 2; if (i < 256) return x * x + i / func(i, x); else return x * x + i / x * x; } 

and do not bring the result of the function to the whole.

 function func(i, x) { i = i * 2; if (i < 256) return x * x + i / func(i, x); else return x * x + i / x * x; } $(document).ready(function(){ $("#calculate").click(function(){ var inp = parseFloat($("#valueIn").val()); var out = inp / func(1, inp); $("#valueOut").val(out); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> Input:<input id="valueIn" type="text" /> <br/><br/> <button type="button" id="calculate">Calculate</button> <br/><br/> Output:<input id="valueOut" type="text" /> 

    The main error lies in the description of the recursive function

      int func(float i, float x) 

    It is indicated that the function returns an int type result. Those. in your case, it turns out that any result is reduced to an integer.

    Thus, the accuracy of calculations is lost.

    To fix this you need to specify that the function returns a float . Or, for greater accuracy, it is worth changing all float to double

    • Both errors are basic: the type of the return value and the bracket in return ((x*x + i) / func(i, x)); . - Igor