Есть исходник программы:
#include <iostream.h>
#include <conio.h>
#include <math.h>
void main(void)
{
start:
float x=5;
int y=2;
cout << «Vvedite 4islon»;
cin >> x;
cout << «Vvedite stepen’n»;
cin >> y;
cout << pow(x,y) << «n»;
getch();
goto start;
}
Программа работает. Но есть один непонятный мне момент.
Компилирую в Borland C++ 3.1 командой bcc.
На выходе получаю exe’шник (если правильно понимаю 16-ти разрядный). Весит 51 Кб. Запускаю.
Хочу найти 308-ю степень числа 10… Выдаёт:
Хочу найти 309-ю степень числа 10… Выдаёт:
Цитата
pow OVERFLOW error
1,797693e+308
Здесь я так понимаю это ограничение представления чисел с плавающей запятой двойной точности 1.79 × 10^308
Затем компилирую с помощью CodeGear C++ Builder 2009 командой bcc32.
На выходе получаю exe’шник (Этот, я так понимаю, уже 32-ти разрядный). Весит 268 Кб. Запускаю.
Хочу найти 38-ю степень числа 10… Выдаёт:
Хочу найти 39-ю степень числа 10… Выдаёт 3 виндузятских message box’а (смотрите приложение внизу):
Цитата
XXX.exe — Ошибка приложения.
Исключение unknown software exception (0xc0000091) в приложении по адресу 0x0040132d…(Ну, там «ОК» — отладка приложения и т.д.)
Потом опять точно такую же ошибку…
И третий message box отличается только адресом:
***
… (0xc0000027) в приложении … 0x7c80df3c
***
И затем естественно приложение аварийно завершается…
Хочу найти 308-ю степень числа 10… Выдаёт то же аварийное завершение (см. чуть выше)…
Ну, а если я пытаюсь найти 309-ю степень то приложения уже не завершается аварийно. Выдаёт следующее сообщение:
Цитата
pow: OVERFLOW error
+INF
Так в чём же фишка ??? Код ведь одинаковый. Значит дело в компиляторах ?
Связано ли это с 16 и 32 разрядностью (но почему то здесь по логике всё наоборот) ?
Или же это связанно с отличием в стандартах ? Разные типы данных в функции pow в зависимости от стандарта?
Может CodeGear намудрили ?
И почему тогда во втором случае программа аварийно завершается даже не объяснив в чём фишка, а в первом случае всё как по маслу и работает даже после переполнения ?
Скомпилировал в QT (32-х разрядную). Всё работает. Только выдаёт сообщение «INF» когда выходит за 1,797693e+308… Здесь значит всё ОК…
Сообщение отредактировано: ToxaTheMan — 11.07.09, 16:15
Прикреплённая картинка
AlexKreep 2 / 1 / 1 Регистрация: 23.11.2017 Сообщений: 100 |
||||
1 |
||||
21.11.2019, 18:44. Показов 1660. Ответов 3 Метки нет (Все метки)
Здравствуйте.
Задача:
__________________
0 |
Модератор 8255 / 5477 / 2249 Регистрация: 21.01.2014 Сообщений: 23,578 Записей в блоге: 3 |
|
22.11.2019, 10:31 |
2 |
выдаёт диалоговое окно с ошибкой А текст ошибки — он очень секретный? А то, может быть, поделились бы?
1 |
Супер-модератор 32451 / 20945 / 8105 Регистрация: 22.10.2011 Сообщений: 36,213 Записей в блоге: 7 |
|
22.11.2019, 10:37 |
3 |
AlexKreep, в момент работы 8-ой строки у тебя переменная x еще не инициализирована, в ней мусор. Поэтому может быть все, что угодно.
А текст ошибки — он очень секретный? Нет. Именно поэтому он записан в заголовке темы.
1 |
D1973 |
22.11.2019, 10:39
|
Не по теме: Вот, блин, слона-то я и не заметил…
0 |
IT_Exp Эксперт 87844 / 49110 / 22898 Регистрация: 17.06.2006 Сообщений: 92,604 |
22.11.2019, 10:39 |
Ошибки вычислений, POW: Domain Error Ошибки Pow: Domain error и Log10: Domain error На другом компьютере exe файл C++ Builder 6 открывается,но выдает ошибку «pow : DOMAIN error» Искать еще темы с ответами Или воспользуйтесь поиском по форуму: 4 |
Содержание
- pow: overflow error
- Повідомлення: 11
- 1 Тема від Betterthanyou 26.10.2015 17:45:33 Востаннє редагувалося Betterthanyou (26.10.2015 18:13:14)
- Тема: pow: overflow error
- 2 Відповідь від Master_Sergius 26.10.2015 18:16:38
- Re: pow: overflow error
- 3 Відповідь від Yola 26.10.2015 18:51:22 Востаннє редагувалося Yola (26.10.2015 18:51:59)
- Re: pow: overflow error
- 4 Відповідь від koala 26.10.2015 18:56:20 Востаннє редагувалося koala (26.10.2015 19:03:50)
- Re: pow: overflow error
- 5 Відповідь від Master_Sergius 26.10.2015 19:06:23
- Re: pow: overflow error
- 6 Відповідь від Betterthanyou 26.10.2015 21:25:49 Востаннє редагувалося Betterthanyou (26.10.2015 21:38:42)
- Re: pow: overflow error
- Thread: Catching an int overflow error
- Catching an int overflow error
pow: overflow error
Ласкаво просимо вас на україномовний форум з програмування, веб-дизайну, SEO та всього пов’язаного з інтернетом та комп’ютерами.
Будемо вдячні, якщо ви поділитись посиланням на Replace.org.ua на інших ресурсах.
Для того щоб створювати теми та надсилати повідомлення вам потрібно Зареєструватись.
Для відправлення відповіді ви повинні увійти або зареєструватися
Повідомлення: 11
1 Тема від Betterthanyou 26.10.2015 17:45:33 Востаннє редагувалося Betterthanyou (26.10.2015 18:13:14)
- Betterthanyou
- TEAM
- Поза форумом
- Звідки: Київ
- Дата реєстрації: 16.05.2014
- Повідомлень: 1 645Репутація: 986
Тема: pow: overflow error
Помилка pow: overflow error
Я хочу порахувати ануїтетні платежі для цього мені потрібно дізнатись коефіцієнт (формули брав звідси http://byhgalter.com/anuїtetnij-sposib- … igidnishe/)
9999999999 * ( 0,0825 * pow( (1 + 0,0825 ), 9999 ) / ( pow( (1 + 0,0825), 9999 ) -1 )
1,0825^9999 — і як це порахувати ?
2 Відповідь від Master_Sergius 26.10.2015 18:16:38
- Master_Sergius
- Користувач
- Поза форумом
- Дата реєстрації: 01.10.2014
- Повідомлень: 1 068Репутація: 805
Re: pow: overflow error
Для с++ певно якісь ліби тра пошукати. Для python — numpy.
А взагалі, ви впевнені, шо у формулі все правильно? Бо там числа кілобайтні виходять, шо не є здорово для підрахунку якихось там платежів
3 Відповідь від Yola 26.10.2015 18:51:22 Востаннє редагувалося Yola (26.10.2015 18:51:59)
- Yola
- Replace Group
- Поза форумом
- Звідки: ukrainian.stackexchange.com
- Дата реєстрації: 16.04.2013
- Повідомлень: 839Репутація: 497
Re: pow: overflow error
Мовиться про кредит на 9999 місяців із відсотковою ставкою 9999999999 * 12 річних, я правильно зрозумів?
4 Відповідь від koala 26.10.2015 18:56:20 Востаннє редагувалося koala (26.10.2015 19:03:50)
- koala
- Лінива тваринка
- На форумі
- Дата реєстрації: 01.05.2013
- Повідомлень: 14 353Репутація: 12212
Re: pow: overflow error
«Річні» у вас не зовсім річні, не буду казати, які саме.
Оцінімо ваше число:
Сума
2
1e10*2^1e4 = 1e10*10^3e3=1e310
Для MSVC long double — синонім double, верхня межа якого — 1e308. Заїхали за межі. Особливо з урахуванням того, що ви спершу обчислюєте великі числа, а потім їх ділите.
Як вибиратися?
— взяти інший компілятор (більшість використовує для long double 80-бітні чи більші, їх вистачить);
— взяти якусь бібліотеку для довгої арифметики, на кшталт boost::multiprecision (чи написати власну);
— дуже обережно обчислювати це число, розклавши pow на цикл — я завищував параметри, можливо, воно таки буде на межі;
— обчислювати не число, а його логарифм;
— пояснити нам, що саме ви хочете зробити і нащо, можливо, будуть інші способи.
5 Відповідь від Master_Sergius 26.10.2015 19:06:23
- Master_Sergius
- Користувач
- Поза форумом
- Дата реєстрації: 01.10.2014
- Повідомлень: 1 068Репутація: 805
Re: pow: overflow error
До речі, якщо раптом ця формула виявиться правильною, то є один простий вихід. Значення буде наближене, але з дуже великою точністю.
Ось дивіться, якшо взяти за х оце ваше страшне pow( (1 + 0,0825), 9999 ), то тоді матимемо:
При таких великих значеннях х, одиницею можна знехтувати, відповідно, просто скоротити на х. Тоді матимете:
6 Відповідь від Betterthanyou 26.10.2015 21:25:49 Востаннє редагувалося Betterthanyou (26.10.2015 21:38:42)
- Betterthanyou
- TEAM
- Поза форумом
- Звідки: Київ
- Дата реєстрації: 16.05.2014
- Повідомлень: 1 645Репутація: 986
Re: pow: overflow error
А взагалі, ви впевнені, шо у формулі все правильно?
Так це коефіцієнт там і має виходити таке число
Мовиться про кредит на 9999 місяців із відсотковою ставкою 9999999999 * 12 річних, я правильно зрозумів?
майже так тільки річні 99%
— пояснити нам, що саме ви хочете зробити і нащо, можливо, будуть інші способи.
Ідея така якщо це значення обрахується правильно то всі решта будуть теж правильні так як програма приймає максимальне число для суми 10 цифр, для термін (місяців) 4, для річних (відсотків) 2
Источник
Thread: Catching an int overflow error
Thread Tools
Search Thread
Display
Catching an int overflow error
Hey everyone, I’ve got some code where I’m calculating a geometric mean:
Now sometimes the value of product gets too big for an integer, and I want to somehow catch this error when it happens. I could change it to a long, but I’d still want to catch the overflow error if it happened with a long, so the type of product doesn’t really matter to my question. (I can potentially get all sorts of crazy numbers in this code and I need to be able to deal with them all!)
I tried enclosing the code in a try/catch block like shown above, but when I stepped through the code with the debugger, it didn’t throw an exception. It just kept trying to multiply product (resulting in some very weird values for product). If product was an invalid entry for the pow function, then an exception was thrown at the pow function.
Any ideas on how I can catch or prevent this overflow error?
That is amazing — I changed it to a double and I never got that error (at least with the parameters I ran the program with). I guess a double can hold larger numbers than an int?
Still, I’m curious if anyone knows how to catch overflow errors like I mentioned in my first post, because that’s something that I’m sure other people may find useful as well!
In C++, there is no such thing as an overflow. If you keep looping with the for loop for( int i = 0; ; i++ ); the value of i would eventually become negative.
Naturally I didn’t feel inspired enough to read all the links for you, since I already slaved away for long hours under a blistering sun pressing the search button after typing four whole words! — Quzah
You. Fetch me my copy of the Wall Street Journal. You two, fight to the death — Stewie
Источник
-
11-04-2008
#1
Registered User
pow: OVERFLOW error
Hi, when i was running my excutable file, i got this error here is the power function i used to calculate the varible:
Code:
int i; for(i = 1; i <= approximation; i++){ pi += pow(12, 0.5)*pow(-1, i+1)/((2*i - 1)*(pow(3, i-1))); }
any ideas?
the error only occur when i pass a large number (over 1000) for approximation, and it runs for a few seconds and in the end it still will print out the correct answer, im just wondering should this be a big deal?
Last edited by skyt; 11-04-2008 at 02:46 PM.
Reason: more info
-
11-04-2008
#2
Banned
I would imagine an overflow took place. What value is approximation?
-
11-04-2008
#3
Registered User
Originally Posted by master5001
I would imagine an overflow took place. What value is approximation?
when i enter 100 or 200 etc the error wouldnt occur, but when i use anything over 1000, it will occur.
however, for the other method of mine,
Code:
int i; for(i = 1; i <= approximation; i++){ pi += 4*pow(-1, i+1)/(2*i-1); }
i passed 40million for approximation and no such error occured
-
11-04-2008
#4
Kernel hacker
I suspect that is caused by the fact that pow(3, n) is much more «growing» than pow(-1, n).
Do you understand what «overflow» and «pow» actually do?
—
MatsCompilers can produce warnings — make the compiler programmers happy: Use them!
Please don’t PM me for help — and no, I don’t do help over instant messengers.
-
11-04-2008
#5
Registered User
Originally Posted by matsp
I suspect that is caused by the fact that pow(3, n) is much more «growing» than pow(-1, n).
Do you understand what «overflow» and «pow» actually do?
—
Matsyea, does it mean the numbers are getting too large for the memory to handle via the power function? is there anything i can do to fix it?
-
11-04-2008
#6
Kernel hacker
Not for «memory to handle», but rather «for the math processing unit» — it is essentially the same as the E you get on a regular calculator if your result is too large (or you divide by zero or some such).
There is really no easy solution to the problem, other than using a different method — on the other hand, I suspect by the time you are even CLOSE to overflow, the calculation isn’t making any changes to the result (because square root of 12 divided by 2 * i-1 * 3 to the power of i will be something like 1E-300 in the calculation leading up to the overflow, and with a double precision float, you only get about 15 or so digits precision, and PI is around 3, so to change the 15th decimal place, the number needs to be bigger than 1E-16 — so you have about 284 too many zeros at the beginnin of the number.
Once your sqrt(12)/X calculation becomes smaller than about 1E-20, you can stop, because it’s not going to change the result. You can check it if you like, by printing the PI value and the sqrt(12)/X value in parallel. Once the number gets small enough, it’s not going to make any changes to PI at all — no matter how many times you do the calculation.
—
MatsCompilers can produce warnings — make the compiler programmers happy: Use them!
Please don’t PM me for help — and no, I don’t do help over instant messengers.
-
11-04-2008
#7
Registered User
Originally Posted by matsp
Not for «memory to handle», but rather «for the math processing unit» — it is essentially the same as the E you get on a regular calculator if your result is too large (or you divide by zero or some such).
There is really no easy solution to the problem, other than using a different method — on the other hand, I suspect by the time you are even CLOSE to overflow, the calculation isn’t making any changes to the result (because square root of 12 divided by 2 * i-1 * 3 to the power of i will be something like 1E-300 in the calculation leading up to the overflow, and with a double precision float, you only get about 15 or so digits precision, and PI is around 3, so to change the 15th decimal place, the number needs to be bigger than 1E-16 — so you have about 284 too many zeros at the beginnin of the number.
Once your sqrt(12)/X calculation becomes smaller than about 1E-20, you can stop, because it’s not going to change the result. You can check it if you like, by printing the PI value and the sqrt(12)/X value in parallel. Once the number gets small enough, it’s not going to make any changes to PI at all — no matter how many times you do the calculation.
—
Matsthat makes perfect sense, in the instruction i will just have to indicate that larger approximation will not help make pi more accurate when it gets too big. i really should have looked into the series itself before i post this problem, it’s purely a math problem rather than a programming problem. You are great!
-
11-05-2008
#8
Kernel hacker
Originally Posted by skyt
that makes perfect sense, in the instruction i will just have to indicate that larger approximation will not help make pi more accurate when it gets too big. i really should have looked into the series itself before i post this problem, it’s purely a math problem rather than a programming problem. You are great!
No, if it was PURELY a math problem, then you have infinite (or relatively huge) precision. Computers limit the precision for the benefit of small size (a double takes up 8 bytes). You can get libraries (or write your own) that does «nearly infinite precission» math, e.g. GMP — limited only by available memory in the machine (or memory available to the process if the machine has HUGE amount of memory). You could quite easily use this to calculate several million digits of PI or some such — but of course, some others have been doing that already…
—
MatsCompilers can produce warnings — make the compiler programmers happy: Use them!
Please don’t PM me for help — and no, I don’t do help over instant messengers.
Внимание!
1. Пользуйтесь тегами кода. — [code] … [/code]
2. Точно указывайте язык, название и версию компилятора (интерпретатора).
3. Название темы должно быть информативным.
В описании темы указываем язык!!!
Наладить общение поможет, если вы подпишитесь по почте на новые темы в этом форуме.
|
Сообщение |
|
Профи
Группа: Пользователи
Репутация: |
Здравствуйте! Столкнулась вот с такой проблемой:
Объясните пожалуйста, в чём тут дело? Как избежать ошибки..? |
|
|
volvo |
Сообщение |
Гость |
Во-первых, randomize () … Во-вторых, этот самый randomize() в цикле запускать нельзя, только перед началом вычислений, однократно. В третьих, желательно переменную yi сделать ЛОКАЛЬНОЙ: double xi = 0., xiStar = 0.; и куда делся domain error? |
|
|
18192123 |
Сообщение |
Профи
Группа: Пользователи
Репутация: |
Цитата(volvo @ 18.10.2009 17:35) и куда делся domain error? я добавила ещё одну ф-ю EXpLow для генерации чисел, распределённых по экспоненциальному з-ну.. Вот как-то так..
|
|
|
volvo |
Сообщение |
Гость |
case 1: Внимательнее с этими вещами… |
|
|
18192123 |
Сообщение |
Профи
Группа: Пользователи
Репутация: |
Ну просто напасть какая-то…Я снова увеличиваю размер генерируемой последовательности (до 60 000 элементов) — и вновь лезут ошибки log10:sign error… И в чём же теперь причина — для меня непостижимо( Сообщение отредактировано: 18192123 — 20.10.2009 1:13 |
|
|
volvo |
Сообщение |
Гость |
Цитата Может рандом выдаёт какое-то недопустимое значение аргумента…? Вполне возможно… Я тебе даже скажу какое значение должно выдаваться, чтобы ты получала то, что получаешь: НОЛЬ… Если rand() вернул 0, то xiStar (естественно) тоже будет = 0, а это некорректные входные данные, это оговорено в описании функции. Так что придется тебе гарантировать, что аргумент log10 не будет нулевым. Ну, например, так: int sure_rand() Если сделать просто: xiStar = static_cast<double>(rand() + 1) / static_cast<double>(RAND_MAX); , то получишь сбой, когда rand() вернет RAND_MAX… Тогда xiStar примет значение > 1, следовательно log10(xiStar) станет больше 0, и ты попытаешься вычислить квадратный корень из отрицательного числа. Поверь, ни к чему хорошему это не приведет… |
|
|
1 чел. читают эту тему (гостей: 1, скрытых пользователей: 0)
Пользователей: 0
Связь с администрацией: bu_gen в домене octagram.name
Amateurtje
- A
- Newbie
- Posts: 43
-
- Logged
Hello,
I receive during compiling the error: Preprocessor.exe Pow: Overflow error
it also started to give an error on one of my symbols: ‘symbol D’
I changed them all into ‘D_’. now it compiles correctly, but the error is still there..
it leaves also the file a.lst which is about 500kb..
while i do not know how they normally look like (there is some asm inside), it is difficult for me to get info for the error from that file..
it is a small program and i use these symbols also in another program without problems..
anybody knows what this error means?
- 1 person likes this.
Amateurtje
- A
- Newbie
- Posts: 43
-
- Logged
I did not find the time yet to break down my program. I hoped anybody could tell me a usual cause of this error to point me in the right direction.. I will use the coming evenings to break down the program…. It appeared while building but solving the errors that he gave at the same moment, did not solve the error… I will let you know what i find or if i have a code snippet i will post it here..
When it appeared, i was introducing a lot of new symbols, and scripts i have used in another program without errors…
I’m away from my computer but fairly sure single letter identifiers are not permitted.
That is why you at least now have a compile.
The code snippet will help us help you when you have time to do that.
John
- 1 person likes this.
Amateurtje
- A
- Newbie
- Posts: 43
-
- Logged
Unbtill now, in other programs, it went never wrong.. I used them to make digits on a 7-segment display. (the 7 1’s and 0′ represent a letter on the display).. Ofcourse, I can make them more letters but it reads nicer in the code when it is 1 letter.
I hope to have energy left this evening
thanks
- 1 person likes this.
The preprocessor is a seperate program to the compiler and uses the computer’s capabilities for its floating point functions. So the Pow is trying to take the power of a value that is too large for it. Hence the overflow error.
Pow can produce extremely large values that are often larger than a compiler or floating point unit can handle.
Amateurtje
- A
- Newbie
- Posts: 43
-
- Logged
As far as I know I do not have a floating pont value (or it sees the symbols as floating points, but they are all byte values). As I understand, Pow is a function, isn’t it.. That, I do not use anywhere…
I have no clue where I use floating point variables in this script (no floats defined), but I will try to break the code down…
The preprocessor uses both integer and floating point for its «built in» expression functions, so even integer values will overflow if they are created too large. But the error indicates it is a floating point overflow.
I have no control over the limits of the C++ compiler’s built in functions that use the computer’s floating point hardware, so it will have limits. Now that 64-bit machines are dominant, I will get back into the preprocessor at some time and make it 64-bit compatible.
- 3 people like this.
Amateurtje
- A
- Newbie
- Posts: 43
-
- Logged
Got it,
IT was the combination:
Symbol B = %00101100
And in the program:
Dig_4 = B 'Dig_4 is a byte variable
Solved by changing to:
Symbol B_ = %00101100
Dig_4 = B_
To be sure, I will change all single letter symbols to «X_»
Thanks for the help
- 1 person likes this.
- Proton BASIC Community
-
►
Proton (Positron) -
►
Proton8 threads -
►
Preprocessor.exe Pow: Overflow error