Nan ind c как исправить

-nan(ind) C++ Решение и ответ на вопрос 2613018

no swear

192 / 166 / 82

Регистрация: 01.07.2016

Сообщений: 942

1

08.04.2020, 00:20. Показов 3985. Ответов 3

Метки нет (Все метки)


Что такое -nan(ind) и как это исправить?

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cmath>
 
long double powDouble(long double a, long double b) {
    long double k = a;
    for(int i = 2; i <= b; ++i) {
        a *= k;
    }
    return a;
}
 
int main() {
    std::ofstream out("c:\out.txt");
    long double lambda = 2., tetta = 400., PiConst = 0.04, beta = 0.6, So = 0.02, L = 750., alpha = 0.5;
    long double y, PiSave, S = 1000000.;
    int VSave, ESave;
    for(int V = 1; V <= 200; ++V) {
        y = lambda * tetta / (long double)V;
        for(int E = 1; E <= 200; ++E) {
            long double Pi;
            if(y != 1.L) {
                Pi = powDouble(y, (long double)E) * (1.L - y) / (1.L - powDouble(y, long double(E + 1)));
            } else {
                Pi = 1.L / (long double)(E + 1);
            }
            out  << std::setprecision(10) << E << "     " << V << "     " << Pi << "   " << PiConst << std::endl;
            if(Pi >= PiConst) {
                
                continue;
            }
            long double STemp = alpha * powDouble((long double)V, (long double)beta) + So * E * L; // S = Sн + Sп = alpha * V^beta + So*E*L
            if(STemp < S) {
                S = STemp;
                PiSave = Pi;
                VSave = V;
                ESave = E;
            }
            //out << E << " " << V << std::endl;
        }
    }
    //out << ESave << " " << VSave << " " << PiSave << " " << S << std::endl;
    return 0;
}

Начиная с E = 106 и V = 1 появляется -nan(ind) а потом исчезает и опять по кругу.



0



Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

08.04.2020, 00:20

Ответы с готовыми решениями:

Ошибка -nan(ind) и nan
Доброго времени суток форумчане! Решаю задачу, в которой необходимо найти площадь треугольника по…

-nan(ind)
нужно вычислить значение функции, вроде сделал все проверки, но все равно при вводе отрицательного…

Ошибка -nan<ind>
#include &quot;pch.h&quot;
#include &lt;iostream&gt;
#include &lt;math.h&gt;
using namespace std;
int main()
{…

Ошибка nan(ind)
Помогите, пожалуйста. Что за ошибка nan(ind) в момент когда y должен быть равен 0

#include…

3

Заклинатель змей

611 / 508 / 213

Регистрация: 30.04.2016

Сообщений: 2,412

08.04.2020, 00:35

2

Лучший ответ Сообщение было отмечено no swear как решение

Решение

no swear, я конечно сто лет не писал не крестах, но зачем pow велосипед, если есть powl()?
https://en.cppreference.com/w/c/numeric/math/pow



1



Вездепух

Эксперт CЭксперт С++

10436 / 5705 / 1553

Регистрация: 18.10.2014

Сообщений: 14,101

08.04.2020, 00:53

3

Лучший ответ Сообщение было отмечено no swear как решение

Решение

Цитата
Сообщение от no swear
Посмотреть сообщение

Начиная с E = 106 и V = 1 появляется -nan(ind) а потом исчезает и опять по кругу.

Так а что вы ожидали произойдет, когда вы начнете вычислять такие гигантские степени, которые не помещаются в диапазон вашего плавающего типа? 800 в 107 степени — это уже чересчур, учитывая, что вы, очевидно, запускаете код в реализации, в которой long double совпадает с double. Функция powDouble возвращает inf, а деление на inf дает вам nan.

В реализации с 80-битным long double у вас был бы шанс «проскочить». А в 64-битный long double вы не помещаетесь.



1



192 / 166 / 82

Регистрация: 01.07.2016

Сообщений: 942

08.04.2020, 01:33

 [ТС]

4

Цитата
Сообщение от DobroAlex
Посмотреть сообщение

я конечно сто лет не писал не крестах, но зачем pow велосипед, если есть powl()?

Та это просто для себя написал так powl тоже можно использовать конечно.

TheCalligrapher, Как я раньше не заметил что переполнение может произойти.

Спасибо за ответы.



0



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

08.04.2020, 01:33

Помогаю со студенческими работами здесь

Ошибка -nan (ind)
Не пойму, как избавится от этой ошибки
#include &quot;pch.h&quot;
#include &lt;iostream&gt;
#include &lt;fstream&gt;…

Выдаёт -nan(ind)
Header.h файл#pragma once
double f(double x);
double h(double a, double b, int n);
double hi(int…

Ошибка -nan(ind)
Как исправить?

#include &lt;iostream&gt;
#include &lt;cmath&gt;
using namespace std;
int main() {
int…

Почему выдает -nan(ind)
#include &lt;iostream&gt;
#include &lt;math.h&gt;

using namespace std;

int main() {

Программа выводит nan ind
Исходные данные:
a=4;
b=5;
eps=0.0001;

Выводит:
xz=-nan(ind);
k=5;
f(x)=-nan(ind);

Что значит -nan(ind)?
Здравствуйте, объясните пожалуйста, что значит -nan(ind)? Вот код программы:
#include &quot;pch.h&quot;…

Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:

4

  • Forum
  • Beginners
  • -nan(ind)?

-nan(ind)?

So I’m writing a program that demonstrates Newton’s method to find a root of an equation. It outputs the estimated value of the root, the the true error and empirical error. After trying to run the program, the true error and estimated error were outputting «-nan(ind)». I stepped through my program and found out that the original function for Newton’s method was returning this «-nan(ind)». What is «-nan(ind)» and how do I avoid it in this program?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
float newton(int count, float aval, float bval)
{
	count++; //Increase count to avoid going past contraint
	float cval = (aval + bval) / 2; //Get midpoint of interval
	float estroot = cval; //Set estimated root equal to midpoint
	cout << estroot << endl; //Output was root is estimated to be right now

	if (count == 20) //If constraint is reached, end recursion
	{
		return estroot;
	}

	else if (equation(aval) * equation(cval) < 0) //If root is in between left value and midpoint,
												  //recur with that interval
	{
		estroot = newton(count, aval, cval);
	}

	else if (equation(cval) * equation(bval) < 0) //If root is in between midpoint and right value,
												  //recur with that interval
	{
		estroot = newton(count, cval, bval);
	}
}

int main()
{
	char end;
	float aval = 1.0; //Initial a value 
	float bval = 4.0; //Initial b value
	float realroot = 2.0; //Real root
	float estroot;
	int count = 0; //count variable to make sure number of iterations does not exceed 20

	estroot = newton(count, aval, bval); //Function to find root
	float trueerr;
	trueerr = realroot - estroot;
	float emperr;
	emperr = equation(estroot) / derivative(estroot);
	cout << "True error = " << trueerr << "nEmpirical error = " << emperr << endl;

	cin >> end; //Pauses program so user can read output
}

NaN is «not a number», possibly resulting from some mathematical faux pas like dividing by 0, or using something undefined. Difficult to tell without full code.

You appear to be implementing the bisection method, not the Newton(-Raphson) method for root-finding. I would expect to see the latter involving a function and its derivative, not your «empirical error».

Can we see your equation( ) function, please: the function whose root you are trying to find.

Also note that your newton function won’t know what to return if equation(cval) is exactly equal to 0 — which, of course, is the root you are seeking.

Is there any reason you are using recursion rather than the more straightforward iteration?

Last edited on

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
float equation(float value)
{
	float output;

	output = 2 * (value * value) - 8; //Equation that we are trying to find root for, can be modified

	return output; //return output of equation
}

float derivative(float value)
{
	float output;

	output = 4 * value;

	return output;
}

Here’s the code for the equation and it’s first derivative. I’m using recursion even though it’s less straightforward because I honestly need more practice in recursion and this gave me a great excuse to try it.

I also tried implementing a condition for equation == 0, but the same problem is still happening

Your original routine newton( ) — your original post — does not return ANYTHING unless count = 20.

To remedy this, simply insert
return estroot;
at the end of this function (between lines 23 and 24 in your original post).

When I checked it, your program then worked.

There are multiple potential problems with your approach.
— Just change your original line 19 to plain
else
Then at least one option will be followed.

— Your method is BISECTION and not NEWTON-RAPHSON (aka Newton’s method).

— It would be far better done by iteration than recursion.

— You don’t check that your original aval and bval actually span the root.

— dividing by the derivative in line 39 will fail for many functions (e.g. y = (x-2)cubed), where the root also has zero slope.

Topic archived. No new replies allowed.

  • Remove From My Forums
  • Question

  • So I’m writing a code to solve for the two angles and missing side of a right triangle. The code has no errors and solves for my side («c») perfectly. However for the angles it prints out -nan(ind). I have been in this class for a total of maybe
    5 class meetings so i don’t know what is going on or how to fix it. So if anyone can plainly explain the issue as though i have no clue what any of the C++ terminology actually is. lol! thank you. Any help is great otherwise just don’t. 

    Here is the code:

    #include <iostream>;
    #include <cmath>;
    using namespace std;
    int main()
    {
    long double a, b, c, A, A1, B1, B, tot1, tot2, tot3;
    char done, an;
    cout << «input value of a n»;
    cin >> a;
    cout << «input value of b n»;
    cin >> b;
    tot1 = a*a + b*b;
    c = sqrt(tot1);
    cout << «c=» << c <<«n»;
    tot2 = (b*b + c*c — a*a) / 2 * b*c;
    A1 = acos(tot2);
    A = A1 * 180 / 3.14;
    cout << A << «n»;
    cin >> done;
    tot3 = (a*a + c*c — b*b) / 2 * a*c;
    B1 = acos(tot3);
    B = B1 * 180 / 3.14;
    cout << B << «n»;
    cin >> done;
    cout << «C is equal to 90 degrees n «;
    system(«pause»);
    return 0;

    };

Answers

  • tot2 = (b*b + c*c — a*a) / 2 * b*c;
    A1 = acos(tot2);

    Your formula for tot2 is incorrect.  You are missing a set of parentheses around the divisor.

    • Proposed as answer by

      Monday, February 15, 2016 9:21 AM

    • Marked as answer by
      May Wang — MSFT
      Wednesday, February 17, 2016 8:16 AM

  • Hi,

    I had test the code,  we can reproduce the issue. In order to solve issue. you should do it :

    tot2 = ((b*b + c*c — a*a) /( 2 * b*c));

    Best Regards,

    Hart

    • Proposed as answer by
      Hart Wang
      Monday, February 15, 2016 9:21 AM
    • Marked as answer by
      May Wang — MSFT
      Wednesday, February 17, 2016 8:16 AM

Понравилась статья? Поделить с друзьями:
  • Nameresolutionfailure как исправить
  • Nameerror name x is not defined что означает эта ошибка
  • Nameerror name print is not defined как исправить
  • Nameap не соответствует формату как исправить
  • Name servers are on the same subnet как исправить