I am new to Java, and I am reading a book on it now. The book does not give me the answer. I am using the following code:
package loanpayments;
public class LoanPayments {
public static void main(String[] args) {
double years = Double.parseDouble(args[0]);
double P = Double.parseDouble(args[1]);
double r = Double.parseDouble(args[2]);
double R = r / 100;
double A = P*(Math.E*Math.exp(R*years));
System.out.println(A);
}
}
I am testing the code with the following values:
years = 3
P = 2340
r = 3.1
First I have to divide r by 100 to get a correct value (in this case it becomes 0.031). The new value of 0.031 becomes capitalized R. Then I use the formula to find A.
I am getting an incorrect output of ~6980.712, when the output should instead be ~2568.060.
I am thinking that I put in the formula wrong, it should be this:
Pe^R(years)
In this case e is Euler's number (~2.71828)
If anyone could advise me on how to fix the formula, or some other mistake, I would much appreciate it, thanks.
Not needed to multiply with another e because Math.exp() is already the exponential function.
Related
I have a dataset of daily prices for a portfolio (I do not have details about the constituents, simply the total daily price). My goal is to select n funds from a pool of funds and create a new portfolio with daily returns as close as possible compared to the original portfolio. I came up with the following formula to describe the problem:
with Yi the original portfolio returns, π the fund weights and X the fund returns.
Additionally, I defined 3 constraints:
To solve this I need to use ojAlgo. I tried the following but I almost instantly got stuck because of 2 issues.
public static void main(String[] [] args){
ExpressionsBasedModel model = new ExpressionsBasedModel();
float[] x1 = getDailyReturns("fund1");
float[] x2 = getDailyReturns("fund2");
float[] x3 = getDailyReturns("fund3");
Variable pi1 = new Variable("pi1");
Variable pi2 = new Variable("pi2");
Variable pi3 = new Variable("pi3");
List<Variable> variables = Arrays.asList(w1, w2, w3);
model.addVariables(variables);
Expression expr = model.addExpression("objective");
expr.setLinearFactor(pi1, x1);
expr.setLinearFactor(pi2, x2);
expr.setLinearFactor(pi3, x3);
expr.weight(1.0);
Optimisation.Result result = model.minimise();
}
First of all, I have X as a vector while .setLinearFactor can only use Number. Secondly I obviously missed something on how I should define the Expression.
Do you know where I could find examples helping me understanding how I am supposed to use the ExpressionBasedModel() for my problem?
Thank you
I'm trying to take user input in the form of myMonthlyPayment, myAnnualInterestRate, and myPrincipal in order to calculate the number of months needed to pay off debt by using The formula I've attached to this post. What I have in eclipse for the formula right now is:
monthsNeeded = ((Math.log(myMonthlyPayment) - Math.log(myMonthlyPayment)
- ((myAnnualInterestRate / 1200.0) * myPrincipal))
/ ((Math.log(myAnnualInterestRate) / 1200.0) + 1.0));
I should be getting an output of 79 months with the inputs I'm using but instead I'm getting -62. I know the formula is correct, I'm almost positive I've made a mistake somewhere in the translation of it into Java. If someone could point it out that would be greatly appreciated!
So I've fixed it, with a sample input and output.
I didn't put much effort into making this code beautiful but you can see that even separating it into 3 parts using method extraction (although I didn't know how to name them, lacking the domain knowledge) made the code easier to understand.
public class Example {
public static void main(String[] args) {
double myMonthlyPayment = 2000;
double myAnnualInterestRate = 5;
double myPrincipal = 200000;
System.out.println(a(myMonthlyPayment));
System.out.println(b(myPrincipal, myAnnualInterestRate, myMonthlyPayment));
System.out.println(c(myAnnualInterestRate));
double monthsNeeded = (a(myMonthlyPayment) - b(myPrincipal, myAnnualInterestRate, myMonthlyPayment))
/ c(myAnnualInterestRate);
System.out.println(monthsNeeded);
}
private static double c(double myAnnualInterestRate) {
return Math.log((myAnnualInterestRate / 1200.0) + 1);
}
private static double b(double myPrinicipal, double myAnnualInterestRate, double myMonthlyPayment) {
return Math.log(myMonthlyPayment - (myAnnualInterestRate / 1200.0) * myPrinicipal);
}
private static double a(double myMonthlyPayment) {
return Math.log(myMonthlyPayment);
}
}
I think this is what you're looking for:
monthsNeeded = (Math.log(myMonthlyPayment) - Math.log(myMonthlyPayment - myAnnualInterestRate / 1200d * myPrincipal)) / Math.log(myAnnualInterestRate / 1200d + 1);
It seems that, in your solution, you weren't calculating your myAnnualInterestRate/1200*myPrincipal inside your second Math.log(...). You had also left some calculations outside of Math.log(...) in the bottom half of your equation.
If you have an equation that does an operation inside a natural log, when you convert that equation to Java code, the operation needs to still be done, inside the natural log:
ln(someNumber + 10)
would be converted to:
Math.log(someNumber + 10),
NOT:
Math.log(someNumber) + 10
Hope this helps and good luck. :)
Can someone let me know how I can do Polynomial Regression with Apache Maths 3.6.1
Below are the data points I used for my testing
60735214881.391304 1520254800000.000000
60697824142.469570 1520258400000.000000
60651182200.208694 1520262000000.000000
60684367132.939130 1520265600000.000000
60676588613.008700 1520269200000.000000
60641816564.869570 1520272800000.000000
60604714824.233510 1520276400000.000000
60580042814.330440 1520280000000.000000
60536134542.469570 1520283600000.000000
60566323732.034780 1520287200000.000000
60578775249.252174 1520290800000.000000
60547382844.104350 1520294400000.000000
60536776546.802160 1520298000000.000000
60474342718.330440 1520301600000.000000
60452725477.286960 1520305200000.000000
60486821569.669560 1520308800000.000000
60247997139.995674 1520312400000.000000
60248432181.426090 1520316000000.000000
60217476247.373920 1520319600000.000000
60170744493.634780 1520323200000.000000
My code looks like below
private void polynomialFitter(List<List<Double>> pointlist) {
final PolynomialCurveFitter fitter = PolynomialCurveFitter.create(2);
final WeightedObservedPoints obs = new WeightedObservedPoints();
for (List<Double> point : pointlist) {
obs.add(point.get(1), point.get(0));
}
double[] fit = fitter.fit(obs.toList());
System.out.printf("\nCoefficient %f, %f, %f", fit[0], fit[1], fit[2]);
}
The coefficients are reported as
Coefficient 12.910025, 0.000000, 0.000000
But these does not seem to be quite correct. If I use the same dataset in
Online Polynimal Regression and in archanoid online regression - both reports same value as 654623237474.68250993904929103762, 28.75921919628759991574, -0.00000000023885199278
Can someone let me know what is going wrong? I have seen this question but that is not helping me.
This has been answered in apache-commons mailing list
Polynomial regression is not the same as curve fitting. To do
polynomial regression in Commons Math, use the
OLSMultipleLinearRegression class, using, X, X^2 etc as the
independent variables (as your second reference above shows).
A sample code is like below
private OLSMultipleLinearRegression getMultipleLinearRegression(List<List<Double>> pointlist) {
OLSMultipleLinearRegression regression = new OLSMultipleLinearRegression();
double y[] = new double[pointlist.size()];
double x[][] = new double[pointlist.size()][2];
int c = 0;
for (List<Double> point : pointlist) {
y[c] = point.get(0);
x[c][0] = point.get(1);
x[c][1] = Math.pow(point.get(1), 2);
regression.newSampleData(y, x);
c++;
}
System.out.printf("\tR2 = %f", regression.calculateRSquared());
return regression;
}
With Commons Math 3.6.1, I get almost identical parameters when fitting a cubic to data using PolynomialCurveFitter and tuk's OLSMultipleLinearRegression suggestion.
The curve gives correct interpolations in the range of the data, but you've got to be careful about extrapolations.
The PolynomialCurveFitter code was half the number of lines of the OLSMultipleLinearRegression code.
I tried to make a program (in Java) that calculates pi with the Chudnovsky algorithm but it has the output NaN (Not a Number). Please help me find mistakes in my code, or improve my code. (I don't have a lot of Java programming knowledge)
You can find Chudnovsky's algorithm here:
https://en.wikipedia.org/wiki/Chudnovsky_algorithm
here is my code:
package main;
public class Class1 {
public static void main(String[] args)
{
double nr1=0,nr2=0,nr3=0,pi=0;
int fo1=1, fo2=1, fo3=1;
for(int i=0; i<=20; i++){
for(int fl1=1; fl1<=(6*i); fl1++){fo1 = fo1 * fl1;}
for(int fl2=1; fl2<=(3*i); fl2++){fo2 = fo2 * fl2;}
for(int fl3=1; fl3<=(i); fl3++){fo3 = fo3 * fl3;}
nr1 = ( (Math.pow(-1, i)) * (fo1) * ((545140134*i) + 13591409) );
nr2 = ( (fo2) * (Math.pow(fo3, i)) * ( Math.pow(Math.pow(640320, 3), (i+(1/2)) )) );
nr3 = 12 * (nr1/nr2);
}
pi = 1/nr3;
System.out.println((Math.PI));
System.out.println(pi);
}
}
There are many issues here.
As Andy mentioned, 1/2 is not 0.5.
You are using integers to compute things like 120! which is completely out of bounds for any primitive type.
f01,f02,f03 should be initialized inside each loop, otherwise they grow even bigger
It is not trivial to fix it. You can take a look at
Error calculating pi using the Chudnovsky algorithm - Java
and
http://www.craig-wood.com/nick/articles/pi-chudnovsky/
for some hints, but don't expect built-in primitive types to work with that algorithm.
I did the problem but I only found out How to do it for one value of x? Here is the program.
public class PointsOnACircleV1 {
public static void main(String[ ] args)
{
double r = 1;
double x = 0.1;
double equation1= Math.pow(r,2);
double equation2= Math.pow(x,2);
double y = Math.sqrt(equation1-equation2);
System.out.println(y);
}
}
I got the correct answer .99 (......)
I need mine to show multiple values of x. Here is how the output should be. Please help if you can.
Use a for loop.
Related Documentation
The for statement.
In order to get it to print multiple values you first need to fill the "String [] args" but you need to ahve them as double to be able to multiply them with other values. In your case that's the X-values, so lets say over the code you posted
public class PointsOnACircleV1 {
//initialize your array with your values
double [ ] args = { 1.0, 0.9, 0.8,.... and so on until you reach 0.1, 0.0};
//you could fill it other more effective ways but just to show you!
public static void main(double[ ] args)
{
double r = 1;
// no need to fill this as you already done
// it double x = 0.1;
for(Iterator<double> i = args.iterator(); args.hasNext(); )
{
//this is the number you want to multiply with
double numbertomultiply = args.next();
double equation1= Math.pow(r,2);
double equation2= Math.pow(numbertomultiply,2);
double y = Math.sqrt(equation1-equation2);
System.out.println(y);
}
}
Just written from my head havent checked it but just to give you a sample :)
EDIT Use the other answers to initialize your array.