You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Npv.java 2.3KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /* ====================================================================
  2. Licensed to the Apache Software Foundation (ASF) under one or more
  3. contributor license agreements. See the NOTICE file distributed with
  4. this work for additional information regarding copyright ownership.
  5. The ASF licenses this file to You under the Apache License, Version 2.0
  6. (the "License"); you may not use this file except in compliance with
  7. the License. You may obtain a copy of the License at
  8. http://www.apache.org/licenses/LICENSE-2.0
  9. Unless required by applicable law or agreed to in writing, software
  10. distributed under the License is distributed on an "AS IS" BASIS,
  11. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. See the License for the specific language governing permissions and
  13. limitations under the License.
  14. ==================================================================== */
  15. package org.apache.poi.ss.formula.functions;
  16. import org.apache.poi.ss.formula.TwoDEval;
  17. import org.apache.poi.ss.formula.eval.ErrorEval;
  18. import org.apache.poi.ss.formula.eval.EvaluationException;
  19. import org.apache.poi.ss.formula.eval.NumberEval;
  20. import org.apache.poi.ss.formula.eval.ValueEval;
  21. import java.util.Arrays;
  22. /**
  23. * Calculates the net present value of an investment by using a discount rate
  24. * and a series of future payments (negative values) and income (positive
  25. * values). Minimum 2 arguments, first arg is the rate of discount over the
  26. * length of one period others up to 254 arguments representing the payments and
  27. * income.
  28. *
  29. * @author SPetrakovsky
  30. * @author Marcel May
  31. */
  32. public final class Npv implements Function {
  33. public ValueEval evaluate(ValueEval[] args, int srcRowIndex, int srcColumnIndex) {
  34. int nArgs = args.length;
  35. if (nArgs < 2) {
  36. return ErrorEval.VALUE_INVALID;
  37. }
  38. try {
  39. double rate = NumericFunction.singleOperandEvaluate(args[0], srcRowIndex, srcColumnIndex);
  40. // convert tail arguments into an array of doubles
  41. ValueEval[] vargs = Arrays.copyOfRange(args, 1 , args.length);
  42. double[] values = AggregateFunction.ValueCollector.collectValues(vargs);
  43. double result = FinanceLib.npv(rate, values);
  44. NumericFunction.checkValue(result);
  45. return new NumberEval(result);
  46. } catch (EvaluationException e) {
  47. return e.getErrorEval();
  48. }
  49. }
  50. }