#include<iostream>
#include<cmath>
using namespace std;
float san= 0.25 ; float var= 0.75;
int findFact(int n)//factorial
{
return n == 1 ? 1 : n * findFact(n - 1);
}
int findNcR(int n, int r)//combination nCr
{
return findFact(n) / (findFact(n - r) * findFact(r));
}
double prob(int s, int v){ //recursive function for probability
if(s>=5) return 1; if(v>=5) return 0;
double sum = 0;
int m = 5-s;
for( int i=0; i<=m; i++){
sum += prob(s+i,v+m-i)*findNcR(m,i)*pow(san,i)*pow(var,m-i);
}
return sum;
}
int main(){
cout<< prob(2,1);
}
In DEV C++, there is no output printed when I compile and run the above code. I think its because of large fractional values involved. Any idea how I can get the output?
Please check the logic you use in your double prob(int s, int v) method.
You are going to infinity recursive like
S=2 V=1
S=2 V=4
S=2 V=7
The base case for your recursion, s==5 or v==5 is never getting hit. As you call your function with s=2, every time the prob function is called it is setting m to 3, and so on the first iteration of the loop (when i==0) it calls prob with s=2 and v=v+3. As you start with v==1, it successively calls prob(2,1), prob(2,4), prob(2,7), etc... and never gets any further.
I don't know what probability distribution you are trying to code so I can't offer any specific advice on how to fix this.
Related
Hi I am trying to calculate the results of the Taylor series expansion for sine to the specified number of terms.
I am running into some problems
Your task is to implement makeSineToOrder(k)
This is templated by the type of values used in the calculation.
It must yield a function that takes a value of the specified type and
returns the sine of that value (in the specified type again)
double factorial(double long order){
#include <iostream>
#include <iomanip>
#include <cmath>
double fact = 1;
for(int i = 1; i <= num; i++){
fact *= i;
}
return fact;
}
void makeSineToOrder(long double order,long double precision = 15){
double value = 0;
for(int n = 0; n < precision; n++){
value += pow(-1.0, n) * pow(num, 2*n+1) / factorial(2*n + 1);
}
return value;
int main()
{
using namespace std;
long double pi = 3.14159265358979323846264338327950288419716939937510L;
for(int order = 1;order < 20; order++) {
auto sine = makeSineToOrder<long double>(order);
cout << "order(" << order << ") -> sine(pi) = " << setprecision(15) << sine(pi) << endl;
}
return 0;
}
I tried debugging
here is a version that at least compiles and gives some output
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
double factorial(double long num) {
double fact = 1;
for (int i = 1; i <= num; i++) {
fact *= i;
}
return fact;
}
double makeSineToOrder(double num, double precision = 15) {
double value = 0;
for (int n = 0; n < precision; n++) {
value += pow(-1.0, n) * pow(num, 2 * n + 1) / factorial(2 * n + 1);
}
return value;
}
int main(){
long double pi = 3.14159265358979323846264338327950288419716939937510L;
for (int order = 1; order < 20; order++) {
auto sine = makeSineToOrder(order);
cout << "order(" << order << ") -> sine(pi) = " << setprecision(15) << sine << endl;
}
return 0;
}
not sure what that odd sine(pi) was supposed to be doing
Apart the obvious syntax errors (the includes should be before your factorial header) in your code:
I see no templates in your code which your assignment clearly states to use
so I would expect template like:
<class T> T mysin(T x,int n=15){ ... }
using pow for generic datatype is not safe
because inbuild pow will use float or double instead of your generic type so you might expect rounding/casting problems or even unresolved function in case of incompatible type.
To remedy that you can rewrite the code to not use pow as its just consequent multiplication in loop so why computing pow again and again?
using factorial function is waste
you can compute it similar to pow in the same loop no need to compute the already computed multiplications again and again. Also not using template for your factorial makes the same problems as using pow
so putting all together using this formula:
along with templates and exchanging pow,factorial functions with consequent iteration I got this:
template <class T> T mysin(T x,int n=15)
{
int i;
T y=0; // result
T x2=x*x; // x^2
T xi=x; // x^i
T ii=1; // i!
if (n>0) for(i=1;;)
{
y+=xi/ii; xi*=x2; i++; ii*=i; i++; ii*=i; n--; if (!n) break;
y-=xi/ii; xi*=x2; i++; ii*=i; i++; ii*=i; n--; if (!n) break;
}
return y;
}
so factorial ii is multiplied by i+1 and i+2 every iteration and power xi is multiplied by x^2 every iteration ... the sign change is hard coded so for loop does 2 iterations per one run (that is the reason for the break;)
As you can see this does not use anything funny so you do not need any includes for this not even math ...
You might want to add x=fmod(x,6.283185307179586476925286766559) at the start of mysin in order to use more than just first period however in that case you have to ensure fmod implementation uses T or compatible type to it ... Also the 2*pi constant should be in target precision or higher
beware too big n will overflow both int and generic type T (so you might want to limit n based on used type somehow or just use it wisely).
Also note on 32bit floats you can not get better than 5 decimal places no matter what n is with this kind of computation.
Btw. there are faster and more accurate methods of computing goniometrics like Chebyshev and CORDIC
I am writing some code that prints out a sum series using a loop and a function.
I intend the equation to look like this
m(i) = (1/2) + (2/3) + ... (i / i + 1)
The problem is that my code always gives me incorrect answers and not printing what it's supposed to. For example, when I input 1 into 1 the answer should be 0.5
This is my code:
#include <iostream>
using namespace std;
void sumSeries(int x);
int main() {
sumSeries(1);
return 0;
}
void sumSeries(int x){
double sum = 0;
for(int i = 0; i < x; i++){
sum = (x/x + 1);
sum += sum;
}
cout<<sum;
}
Indeed, you overwrite your sum but also take care of your integer division.
You may change it as sum += i/(double)(i + 1);
#include <iostream>
using namespace std;
void sumSeries(int x);
int main() {
sumSeries(5);
return 0;
}
void sumSeries(int x){
if (x<0)
{
return;
}
double sum = 0;
for(int i = 0; i < x; i++){
sum += i/(double)(i + 1);
}
cout<<sum;
}
I see two problems in your code.
First: (x/x+1) != (x/(x+1)), in this case C++ obeys the normal point before line calculation rules.
Second: You are overwriting your sum in each iteration, instead of that you should direct add to sum: sum+=x/(x+1)
And a third issue, as noted by Simon Kraemer, is that you are using integer division, to get the correct results you must cast at least one of the operands to a floating point number.
What you want is:
void sumSeries(int x){
double sum = 0;
for(int i = 1; i <= x; i++){ // include i in the list
sum += static_cast<double>(i)/(i + 1); // force the operation as double
}
cout<<sum;
}
your mathematical expression has something not normal. Do you mean M(i)= sum(1-i){i/i+1}? , or 1/2 and 1/3 are constants?
in your case as gerum answered it is a small Operator Precedence problem to learn how the C++ compiler prioritize the operators follow here.
your function also should have a guard against zero denominator (undefined values).
Also you should observe that you take int/int division which will ignore the remaining value. then you should consider that by converting the numerator or the denominator to double before the division here .
then your code should be:
#include <iostream>
using namespace std;
void sumSeries(int x);
int main() {
sumSeries(1);
return 0;
}
void sumSeries(int x){
double sum = 0;
for(int i = 0; i < x; i++){
if ((x+1)!=0){
sum += (double)x/(x + 1);
}
// the else will apply only if x==-1
else {
cout<<"the denominator is zero"<<endl;
throw;
}
}
cout<<sum;
}
The question asks me to find the greatest power devisor of (number, d) I found that the function will be like that:
number % d^x ==0
I've done so far using for loop:
int gratestDevisor(int num, int d){
int p = 0;
for(int i=0; i<=num; i++){
//num % d^i ==0
if( (num % (int)pow(d,i))==0 )
p=i;
}
return p;
}
I've tried so much converting my code to recursion, I can't imagine how to do it and I'm totally confused with recursion. could you give me a tip please, I'm not asking you to solve it for me, just some tip on how to convert it to recursion would be fine.
Here is a simple method with recursion. If ddivides num, you simply have to add 1 to the count, and divide num by d.
#include <stdio.h>
int greatestDevisor(int num, int d){
if (num%d) return 0;
return 1 + greatestDevisor (num/d, d);
}
int main() {
int num = 48;
int d = 2;
int ans = greatestDevisor (num, d);
printf ("%d\n", ans);
return 0;
}
A recursive function consist of one (or more) base case(es) and one (or more) calls to the function itself. The key insight is that each recursive call reduces the problem to something smaller till the base case(es) are reached. State (like partial solutions) are either carried in arguments and return value.
You asked for a hint so I am explicitly not providing a solution. Others have.
Recursive version (which sucks):
int powerDividing(int x, int y)
{
if (x % y) return 0;
return 1 + powerDividing(x/y, y);
}
I'm writing a recursion function to find the power of a number and it seems to be compiling but doesn't output anything.
#include <iostream>
using namespace std;
int stepem(int n, int k);
int main()
{
int x, y;
cin >> x >> y;
cout << stepem(x, y) << endl;
return 0;
}
int stepem(int n, int k)
{
if (n == 0)
return 1;
else if (n == 1)
return 1;
else
return n * stepem(n, k-1);
}
I tried debugging it, and it says the problem is on this line :
return n * stepem(n, k-1);
k seems to be getting some weird values, but I can't figure out why?
You should be checking the exponent k, not the number itself which never changes.
int rPow(int n, int k) {
if (k <= 0) return 1;
return n * rPow(n, --k);
}
Your k is getting weird values because you will keep computing until you run out of memory basically, you will create many stack frames with k going to "-infinity" (hypothetically).
That said, it is theoretically possible for the compiler to give you a warning that it will never terminate - in this particular scenario. However, it is naturally impossible to solve this in general (look up the Halting problem).
Your algorithm is wrong:
int stepem(int n, int k)
{
if (k == 0) // should be k, not n!
return 1;
else if (k == 1) // this condition is wrong
return 1;
else
return n * stepem(n, k-1);
}
If you call it with stepem(2, 3) (for example), you'll get 2 * 2 * 1 instead of 2 * 2 * 2 * 1. You don't need the else-if condition:
int stepem(int n, unsigned int k) // unless you want to deal with floating point numbers, make your power unsigned
{
if (k == 0)
return 1;
return n * stepem(n, k-1);
}
Didn't test it but I guess it should give you what you want and it is tail recursive.
int stepemi(int result, int i int k) {
if (k == 0 && result == i)
return 1;
else if (k == 0)
return result;
else
return stepem(result * i, i, k-1);
}
int stepem(int n, int k) {
return stepemi(n, n, k);
}
The big difference between this piece of code and the other example is that my version could get optimized for tail recursive calls. It means that when you call stepemi recursively, it doesn't have to keep anything in memory. As you can see, it could replace the variable in the current stack frame without having to create a new one. No variable as to remain in memory to compute the next recursion.
If you can have optimized tail recursive calls, it also means that the function will used a fixed amount of memory. It will never need more than 3 ints.
On the other hand, the code you wrote at first creates a tree of stackframe waiting to return. Each recursion will add up to the next one.
Well, just to post an answer according to my comment (seems I missed adding a comment and not a response :-D). I think, mainly, you have two errors: you're checking n instead of k and you're returning 1 when power is 1, instead of returning n. I think that stepem function should look like:
Edit: Updated to support negative exponents by #ZacHowland suggestion
float stepem(int n, int k)
{
if (k == 0)
return 1;
else
return (k<0) ?((float) 1/n) * stepem(n, k+1) :n * stepem(n, k-1);
}
// Power.cpp : Defines the entry point for the console application.
//
#include <stream>
using namespace std;
int power(int n, int k);
void main()
{
int x,y;
cin >>x>>y;
cout<<power(x,y)<<endl;
}
int power(int n, int k)
{
if (k==0)
return 1;
else if(k==1) // This condition is working :) //
return n;
else
return n*power(n,k-1);
}
your Program is wrong and it Does not support negative value given by user,
check this one
int power(int n, int k){
'if(k==0)
return 1;
else if(k<0)
return ((x*power(x,y+1))*(-1));
else
return n*power(n,k-1);
}
sorry i changed your variable names
but i hope you will understand;
#include <iostream>
using namespace std;
double power(double , int);// it should be double because you also need to handle negative powers which may cause fractions
int main()
{
cout<<"please enter the number to be powered up\n";
double number;
cin>>number;
cout<<"please enter the number to be powered up\n";
int pow;
cin>>pow;
double result = power(number, pow);
cout<<"answer is "<<result <<endl;
}
double power( double x, int n)
{
if (n==0)
return 1;
if (n>=1)
/*this will work OK even when n==1 no need to put additional condition as n==1
according to calculation it will show x as previous condition will force it to be x;
try to make pseudo code on your note book you will understand what i really mean*/
if (n<0)
return x*power(x, n-1);
return 1/x*power(x, n+1);// this will handle negative power as you should know how negative powers are handled in maths
}
int stepem(int n, int k)
{
if (k == 0) //not n cause you have to vary y i.e k if you want to find x^y
return 1;
else if (k == 1)
return n; //x^1=x,so when k=1 it should be x i.e n
else
return n * stepem(n, k-1);
}
I'm trying to compute the value of cos x using the Taylor series formula
infinity
---- 2k
\ k x
cos(x) = / (-1) * -------------
---- (2k)!
k=0
Shown graphically at http://ppt.cc/G,DC
Here is my program.
#include "stdafx.h"
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
double sum=0.0,sum1=0.0;
double x;
cin>>x;
for(int i=0 ; i<=10 ; i=i+1 )
{
for(int i=1 ; i<=20 ; i=i+1)
{
sum1=i*sum1+sum1;
}
sum=pow(-1,(double)i)*pow(x,(double)(2*i))/sum1+sum;
}
cout<<"Sum : "<<sum<<endl;
system("pause");
return 0;
}
The output is -1.#IND
Why?
How can I change the order of "sum1" to make it work right?
You're using i as the name of the controlling variables for two for-loops that are nested inside each other. That won't work the way you expect.
Next, sum1 is 0. No matter how many times you multiply zero by things and add zero to it, it's still zero. Then you divide by zero, which is why your final answer is NaN (not-a-number).
You need to fix the computation of factorial. Why don't you write a factorial function and test it by itself first?
You're redeclaring i inside your inner loop.
for(int i=0 ; i<=10 ; i=i+1 )
{
for(int i=1 ; i<=20 ; i=i+1)
It's been a while since I've done C, but I'm fairly sure that's an error.
Many things are a bit weird.
First : Please write ANSI C++ and try not to adopt the Microsoft Stuff, I don't really know but I guess those are for the pro's. Lets just stick to the basic stuff.
Here is what you should do :
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
double factorial(double fac)
{
if(fac == 0)
return 1;
return fac * factorial(fac - 1);
}
int main(int argc, char* argv[])
{
double sum=0.0;
double x;
cin >> x;
for ( int i = 0 ; i <= 10 ; i++ )
{
double divisor = factorial ( 2 * i );
if(divisor != 0.0)
{
sum += (double)( (pow( -1 , i ) * pow (x , 2*i )) / divisor );
}
}
cout<<"Sum : "<<sum<<endl;
//system("pause");
return 0;
}
You are not only calculating the Factorial in a weird way, but you also dont use the math operators correctly and you dont perform the math calculation as you would like to. Also the code you wrote is very weird that way because it does not make it clear (not even for you from what I understand). Look at what others commented too. They are right.
When you divide by 0, the result becomes infinity (which prints out as -1.#IND)
Muggen has given a good naive way of doing this, recomputing the whole factorial each time, and using the pow function to compute the alternating sign in the formula. But there are improvements that you can make to this code faster.
The Factorial function in one iteration of the loop can take advantage of the fact that you already multiplied most of the terms you need in the prior iterations of the loop.
The exponent (-1)^k is just a way to alternate between addition and subtraction -- you can replace that by having a variable that alternates its sign every iteration through the loop. (There are other ways to do this besides what I showed here, the point is that you don't need to call the pow() function to do it.)
The other power function x^(2k) can also be unrolled the same way.
I eliminated the first iteration of the loop, because I could calculate it in my head (it was 1.0, for any x), and set the initial value of sum to 1.0. This way factorial doesn't ever get multiplied by 0.
Try this instead
#include "stdafx.h"
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
double x;
cin>>x;
double sum=1.0, factorial=1.0, sign=-1.0, power=1.0;
for(int i=1 ; i<=10 ; i=i+1 )
{
factorial*= (2*i-1) * 2*i;
power *= x * x;
sum += sign * power/factorial;
sign = -sign;
}
cout<<"Sum : "<<sum<<endl;
system("pause");
return 0;
}
It does not appear that you are computing the factorial correctly. should be
sum1 = 1.0;
for(int k=1 ; k<=i*2 ; k=k+1)
{
sum1 *= k;
}
Notice that the factorial terminates a at your outer loop i, and not the fixed number 20, When i is 5, you don't want 20!, you want (2*5)!.