I am trying to print out the variable *loan_Amt* when the monthly payment exceeds/is equal to the 30% amount that is found in the *monthly_payment* function. This is my first attempt at writing a c++ program with functions!
#include<iostream>
#include<conio.h>
#include<string>
#include<iomanip>
#include<math.h>
using namespace std;
double monthly_Payment (double amt_Amt)
{
double r;
r = ( amt_Amt/ 12) * 30/100;
return (r);
}
double interest_Calculate(double interest_Amt)
{
double r;
r = (interest_Amt * .010);
return (r);
}
//double loan_Calculate()
//{
//int x = interest_Calculate(interest_Rate);
//double monthly = (loan_Amt * x) / (1 - pow(1.0 + i,-(12*30)));
//for (((int loan_Amt = 20000) * (x/12)) / pow(1.0 + i,-(12*30)); loan_Amt>0; loan_Amt++);
//}
int main()
{
double gross_Salary;
double interest_Rate;
int x;
int i;
double monthly;
std::cout << "Please enter your yearly gross salary:";
std::cin >> gross_Salary;
std::cout << "Please enter an interest rate:";
std::cin >> interest_Rate;
int z;
z = monthly_Payment (gross_Salary);
std::cout << "The target (30 percent of monthly salary) monthly payment range is:" << z;
for ( int loan_Amt = 0; loan_Amt <= 5000000; x++ ) {
do {
x = interest_Calculate(interest_Rate);
monthly = (loan_Amt * x) / (1 - pow(1.0 + x,-(12*30)));
std::cout << loan_Amt;
} while (monthly >= z );
}
getch();
return 0;
}
The for loop has problem, I think,
for ( int loan_Amt = 0; loan_Amt <= 5000000; x++ ) {
do {
x = interest_Calculate(interest_Rate);
monthly = (loan_Amt * x) / (1 - pow(1.0 + x,-(12*30)));
std::cout << loan_Amt;
} while (monthly >= z );
}
loan_Amt will never change its value, so this is an infinite loop.
This line in the do-while loop,
std::cout << loan_Amt;
will always print zero
Related
Question:
Write C++ function to evaluate the following formula for a given x:
The following code was designed in C++ on Visual Studio to be a solution of the above mentioned problem. However whenever I run the code what I am returned is the value of x; or the same value I input.
I don't understand what the problem may be, so I would appreciate any help given.
#include <iostream>
using namespace std;
unsigned long fact(int n) {
if (n <= 1) {
return 1;
}
else {
return n * fact(n - 1);
}
}
unsigned long f(int x, int n) {
static unsigned long term;
static unsigned long sum = 0;
do {
term = pow(x, (2 * n + 1)) / fact((2 * n) + 1);
n++;
sum += term;
} while (term < 0.000001);
return sum;
}
int main() {
int y = 0;
int x;
cout << "enter x" << endl;
cin >> x;
cout << f(x, y) << endl;
system("pause");
}
I suggest you don't calculate powers and factorials on each iteration. Each next term can be generated by multiplying the previous one by x^2 / [n(n+1)]:
double sinh_in_disguise(const double x) {
const double x_sq = x * x;
double term = x;
double sum = 0;
double n = 2;
while (true) {
const double new_sum = sum + term;
if (new_sum == sum)
break;
sum = new_sum;
term *= x_sq / (n * (n + 1));
n += 2;
}
return sum;
}
int main() {
std::cout.precision(16);
double x = 2.019;
std::cout << sinh_in_disguise(x) << std::endl; // prints 3.699001094869803
std::cout << std::sinh(x) << std::endl; // prints 3.699001094869803
}
put double datatype in the whole code and it will work perfectly
I'm trying to implement logistic regression in C++, but the predictions I'm getting are not even close to what I am expecting. I'm not sure if there is an error in my understanding of logistic regression or the code.
I have reviewed the algorithms and messed with the learning rate, but the results are very inconsistent.
double theta[4] = {0,0,0,0};
double x[2][3] = {
{1,1,1},
{9,9,9},
};
double y[2] = {0,1};
//prediction data
double test_x[1][3] = {
{9,9,9},
};
int test_m = sizeof(test_x) / sizeof(test_x[0]);
int m = sizeof(x) / sizeof(x[0]);
int n = sizeof(theta) / sizeof(theta[0]);
int xn = n - 1;
struct Logistic
{
double sigmoid(double total)
{
double e = 2.71828;
double sigmoid_x = 1 / (1 + pow(e, -total));
return sigmoid_x;
}
double h(int x_row)
{
double total = theta[0] * 1;
for(int c1 = 0; c1 < xn; ++c1)
{
total += theta[c1 + 1] * x[x_row][c1];
}
double final_total = sigmoid(total);
//cout << "final total: " << final_total;
return final_total;
}
double cost()
{
double hyp;
double temp_y;
double error;
for(int c1 = 0; c1 < m; ++c1)
{
//passes row of x to h to calculate sigmoid(xi * thetai)
hyp = h(c1);
temp_y = y[c1];
error += temp_y * log(hyp) + (1 - temp_y) * log(1 - hyp);
}// 1 / m
double final_error = -.5 * error;
return final_error;
}
void gradient_descent()
{
double alpha = .01;
for(int c1 = 0; c1 < n; ++c1)
{
double error = cost();
cout << "final error: " << error << "\n";
theta[c1] = theta[c1] - alpha * error;
cout << "theta: " << c1 << " " << theta[c1] << "\n";
}
}
void train()
{
for(int epoch = 0; epoch <= 10; ++epoch)
{
gradient_descent();
cout << "epoch: " << epoch << "\n";
}
}
vector<double> predict()
{
double temp_total;
double total;
vector<double> final_total;
//hypothesis equivalent function
temp_total = theta[0] * 1;
for(int c1 = 0; c1 < test_m; ++c1)
{
for(int c2 = 0; c2 < xn; ++c2)
{
temp_total += theta[c2 + 1] * test_x[c1][c2];
}
total = sigmoid(temp_total);
//cout << "final total: " << final_total;
final_total.push_back(total);
}
return final_total;
}
};
int main()
{
Logistic test;
test.train();
vector<double> prediction = test.predict();
for(int c1 = 0; c1 < test_m; ++c1)
{
cout << "prediction: " << prediction[c1] << "\n";
}
}
start with a very small learning rate wither larger iteration number at try. Haven`t tested ur code. But I guess the cost/error/energy jumps from hump to hump.
Somewhat unrelated to your question, but rather than computing e^-total using pow, use exp instead (it's a hell of a lot faster!). Also there is no need to make the sigmoid function a member func, make it static or just a normal C func (it doesn't require any member variable from your struct).
static double sigmoid(double total)
{
return 1.0 / (1.0 + exp(-total));
}
I made a c++ program that calculates sin without math.h. Im using this algorithm for my program https://ibb.co/bTnQnS. I enter 45 degrees, the program converts degrees to radians, the program uses the algorithm, and the program outputs -0.868597. The program should output 0.70710678 or √2/2. What am I doing wrong with the algorithm?
Code:
#include "stdafx.h"
#include <iostream>
using namespace std;
double sin(int input, int decimal_count);
int factorial(int n);
double deg_to_rad(int deg);
double power(double base, int power);
int main(){
double angle;
int decimal;
cout << sin(45,8) << endl;
//end
system("pause");
return 0;
}
double sin(int input, int accuracy) {
int odds = 3;
double sin;
double rads = deg_to_rad(input);
for (int i = 1; i <= accuracy; i += 1) {
if (i==1) {
sin = power(rads, odds) / factorial(odds);
}
else if (i%2==0) {
sin = (power(rads, odds) / factorial(odds)) + sin;
}
else {
sin = (power(rads, odds) / factorial(odds)) - sin;
}
odds = odds + 2;
}
sin = sin - rads;
return sin;
}
int factorial(int n) {
int fact = 1;
for (int j = 1; j <= n; j+=1) {
fact = fact * j;
}
return fact;
}
double deg_to_rad(int deg) {
return deg*(3.14159265/180);
}
double power(double base, int power) {
double ans = 1;
for (int k = 1; k <= power; k+=1) {
ans = ans * base;
}
return ans;
}
your taylor series expansion function is incorrect. :)
you have to disregard all even terms.
I have fixed it for you (i removed some windows specific stuff as I don;t have a windows machine: the stdfax.h header and the calls to pause were removed)
# include <cstdlib>
# include <iostream>
using namespace std;
double sin(int input, int decimal_count);
int factorial(int n);
double deg_to_rad(int deg);
double power(double base, int power);
int main(){
double angle;
int decimal;
cout << "The sine value is: " << sin(45,8) << endl;
//end
system("sleep 2");
return 0;
}
double sin(int input, int accuracy) {
int odds = 3;
double sin;
double rads = deg_to_rad(input);
bool negative_flag = true;
cout << "You entered " << input << " degrees" << endl;
cout << "This is " << rads << " radians" << endl;
sin = rads;
for (int taylor_term = 3; taylor_term <= 7; taylor_term += 2) {
double term = (double)(power(rads, taylor_term) / factorial(taylor_term));
if (negative_flag) {
term = -1 * term;
}
negative_flag = !(negative_flag);
sin += term;
}
return sin;
}
int factorial(int n) {
int fact = 1;
for (int j = 1; j <= n; j+=1) {
fact = fact * j;
}
return fact;
}
Running this output
You entered 45 degrees
This is 0.785398 radians
The sine value is: 0.707106
Explanation
The taylor series expansion for sine is a series of terms with odd taylor's coefficients that alternate in sign. In my code the alternating signs is effected by the flag. I've also taken into account only the first 3 terms of the taylor series expansion.
Other than that, the line double term = (double)(power(rads, taylor_term) / factorial(taylor_term)); calculates every term in the taylor series expansion.
negative_flag = !(negative_flag); resets the flag sign for the next term.
Addressing your comment and where your code was a bit wrong
Below is your sin func with minimal changes to make it work.
What you were doing wrong
These are just minimal edits, performing these edits would naturally be followed up with some code style cleanup. eg: the if and else block(not else if) have almost the exact same code
sin was not being initialized before being modified
the attribution to correct signs the taylor terms in the if blocks was not correct.
the extra subtraction of rads at the end from sin was not required. Once these things were fixed, your code works :)
int odds = 3;
double sin ;
double rads = deg_to_rad(input);
sin = rads;
for (int i = 1; i <= accuracy; i += 1) {
if (i==1) {
sin = sin - power(rads, odds) / factorial(odds);
}
else if (i%2==0) {
sin = (power(rads, odds) / factorial(odds)) + sin;
}
else {
sin = -(power(rads, odds) / factorial(odds)) + sin;
}
odds = odds + 2;
}
return sin;
Here is my code so far. There seems to be soemthing wrong since I keep getting an incorrect answer. I am writing in a text file that is formatted:
2
3.0 1.0
2 being the size of the array and then 3.0 and 1.0 being the coefficients. Hopefully I didnt miss much in my explanation. Any help would be greatly appreciated.
Thanks
double polyeval(double* polyarray, double x, int arraySize)
{
//int result = 0;
if(arraySize == 0)
{
return polyarray[arraySize];
}
//result += x*(polyarray[arraySize]+polyeval(polyarray,x,arraySize-1));
return polyarray[arraySize-1]+ (x* (polyeval(polyarray,x,arraySize-1)));
//return result;
}
int main ()
{
int arraySize;
double x;
double *polyarray;
ifstream input;
input.open("polynomial.txt");
input >> arraySize;
polyarray = new double [arraySize];
for (int a = arraySize - 1; a >= 0; a--)
{
input >> polyarray[a];
}
cout << "For what value x would you like to evaluate?" << endl;
cin >> x;
cout << "Polynomial Evaluation: " << polyeval(polyarray, x, arraySize);
delete [] polyarray;
}
the idea that if i read in a text file of that format varying in size that it will solve for any value x given by the user
Jut taking a wild guess
for (int a = arraySize - 1; a >= 0; a--)
// ^^
{
input >> polyarray[a];
}
One error is here:
for (int a = arraySize - 1; a > 0; a--)
{ //^^should be a >=0
input >> polyarray[a];
}
You are missing some entry this way.
The recursive function should look like the following:
int polyeval(double* polyarray, double x, int arraySize)
{
if(arraySize == 1)
{
return polyarray[arraySize-1];
}
return x*(polyarray[arraySize-1]+polyeval(polyarray,x,arraySize-1));
}
The problem is mainly with the definition of the polynomial coefficients.
Your code assumes a polynomial on the form:
x( p(n) + x( p(n-1) + x( p(n-2) + ... x(p(1) + p(0)))..))
This line:
result += x*(polyarray[arraySize]+polyeval(polyarray,x,arraySize-1));
Should become:
result += pow(x,arraySize)*polyarray[arraySize]+polyeval(polyarray,x,arraySize-1);
This way the polynomial is defined correctly as p(n)x^n + p(n-1)x^(n-1) ... + p1 x + p0
Couldn't work out exactly what you were trying to do, or why you were using recursion. So I whipped up a non-recursive version that seems to give the right results.
#include <iostream>
using namespace std;
double polyeval(const double* polyarray, double x, int arraySize) {
if(arraySize <= 0) { return 0; }
double value = 0;
const double * p = polyarray + (arraySize-1);
for(int i=0; i<arraySize; ++i) {
value *= x;
value += *p;
p--;
}
return value;
}
int main () {
const int arraySize = 3;
const double polyarrayA[3] = {0.0,0.0,1.0}; // 0 + 0 x + 1 x^2
const double polyarrayB[3] = {0.0,1.0,0.0}; // 0 + 1 x + 0 x^2
const double polyarrayC[3] = {1.0,0.0,0.0}; // 1 + 0 x + 0 x^2
cout << "Polynomial Evaluation A f(x) = " << polyeval(polyarrayA, 0.5, arraySize)<<std::endl;
cout << "Polynomial Evaluation B f(x) = " << polyeval(polyarrayB, 0.5, arraySize)<<std::endl;
cout << "Polynomial Evaluation C f(x) = " << polyeval(polyarrayC, 0.5, arraySize)<<std::endl;
}
You can see it running here:
http://ideone.com/HE4r6x
doing a C++ approximation of Pi using a random number generator, output works exactly as expected on my AMD 64 machine running Ubuntu, however on my school machine the second algorithm I've implemented is broken, and would love some insight as to why. Code is as follows:
#ifndef RANDOMNUMBER_H_
#define RANDOMNUMBER_H_
class RandomNumber {
public:
RandomNumber() {
x = time(NULL);
m = pow(2, 19); //some constant value
M = 65915 * 7915; //multiply of some simple numbers p and q
method = 1;
}
RandomNumber(int seed) {
x = ((seed > 0) ? seed : time(NULL));
m = pow(2, 19); //some constant value
method = 1; //method number
M = 6543 * 7915; //multiply of some simple numbers p and q
}
void setSeed(long int seed) {
x = seed; //set start value
}
void chooseMethod(int method) {
this->method = ((method > 0 && method <= 2) ? method : 1); //choose one of two method
}
long int linearCongruential() { //first generator, that uses linear congruential method
long int c = 0; // some constant
long int a = 69069; //some constant
x = (a * x + c) % m; //solution next value
return x;
}
long int BBS() { //algorithm Blum - Blum - Shub
x = (long int) (pow(x, 2)) % M;
return x;
}
double nextPoint() { //return random number in range (-1;1)
double point;
if (method == 1) //use first method
point = linearCongruential() / double(m);
else
point = BBS() / double(M);
return point;
}
private:
long int x; //current value
long int m; // some range for first method
long int M; //some range for second method
int method; //method number
};
#endif /* RANDOMNUMBER_H_ */
and test class:
#include <iostream>
#include <stdlib.h>
#include <math.h>
#include <iomanip>
#include "RandomNumber.h"
using namespace std;
int main(int argc, char* argv[]) {
cout.setf(ios::fixed);
cout.precision(6);
RandomNumber random;
random.setSeed(argc);
srand((unsigned) time(NULL));
cout << "---------------------------------" << endl;
cout << " Monte Carlo Pi Approximation" << endl;
cout << "---------------------------------" << endl;
cout << " Enter number of points: ";
long int k1;
cin >> k1;
cout << "Select generator number: ";
int method;
cin >> method;
random.chooseMethod(method);
cout << "---------------------------------" << endl;
long int k2 = 0;
double sumX = 0;
double sumY = 0;
for (long int i = 0; i < k1; i++) {
double x = pow(-1, int(random.nextPoint() * 10) % 2)
* random.nextPoint();
double y = pow(-1, int(random.nextPoint() * 10) % 2)
* random.nextPoint();
sumX += x;
sumY += y;
if ((pow(x, 2) + pow(y, 2)) <= 1)
k2++;
}
double pi = 4 * (double(k2) / k1);
cout << "M(X) = " << setw(10) << sumX / k1 << endl; //mathematical expectation of x
cout << "M(Y) = " << setw(10) << sumY / k1 << endl; //mathematical expectation of y
cout << endl << "Pi = " << pi << endl << endl; //approximate Pi
return 0;
}
The second method returns 4.000 consistently on my lab machine, yet returns a rather close approximation on my personal machine.
For one thing, the BBS generator as you're using it will always return 1.
Since your program takes no arguments, presumably its argc will be 1. You pass argc as the seed (why?), so the initial value of x is 1.
BBS() has the following logic:
x = (long int) (pow(x, 2)) % M;
Clearly, 1 squared modulo M gives 1, so x never changes.
When you run the simulation with such a generator, your program will always output 4.
P.S. Wikipedia has the following to say about the initial value x0 for Blum Blum Shub:
The seed x0 should be an integer that's co-prime to M (i.e. p and q are not factors of x0) and not 1 or 0.