# Nested if statements better formulation

**URL:** <https://discourse.julialang.org/t/nested-if-statements-better-formulation/49715>\
**Category:** New to Julia\
**Tags:** question, performance, optim, optimization\
**Created:** [November 7, 2020, 1:08am UTC](https://discourse.julialang.org/t/nested-if-statements-better-formulation/49715 "2020-11-07T01:08:50Z")\
**Posts on this page:** 1\
**Showing post:** 9

<div class="post-metadata">

**Author:** ![optimist](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/optimist/32/14797_2.png) [@optimist](https://discourse.julialang.org/u/optimist)\
**Post date:** [November 7, 2020, 7:50pm UTC](https://discourse.julialang.org/t/nested-if-statements-better-formulation/49715/9 "2020-11-07T19:50:20Z")

</div>

> [@hendri54](#):
>
> - Find the non-zero values of `cf` that will be actually used in the npv calculations.
> - Run the optimizer on `npv` to find the `irr` . This is done over various predefined intervals until a solution is found.

In the `irr(cf)` function, the first `if` and `elseif` statements are intended to exclude the cases where there will be no solution. Specifically, if the first element in `cf` is zero and there are any other non-zero elements, then it should return `Inf`. If the first element in `cf` is non-zero but the remainder are zeros then it should return `NaN`.

Now, if these two conditional statements are not true then the optimizer is run on `npv` to find `irr`. The `npv` will use all elements of `cf` including zeros (of course excluding the cases that would fall in the first two conditional statements), e.g.

```julia
julia> irr([-100,0,10,10,0,0,110])
0.049594202242656926

```

> [@hendri54](#):
>
> What if all are zero?

I should have added an `if` statement to return `NaN` or a numerical error in this case.

The optimizer may fail to converge if the bounds are set too wide or give a negative result when a positive result is possible. This is the reason I am changing the bounds.

> [@hendri54](#):
>
> For the optimization, I would set up the bounds as a Vector of Vectors (or similar). Then iterate over the bounds until `optimize` returns something near 0.

This is the bit I am struggling with. I can define the bounds as below, but I do not understand how to iterate over them until the convergence criteria is satisfied, probably a `while` loop is required. How should I use the loop?

```julia
lb= [0.0,1.0,-1.0,-1.0e8]  
up=[1.0,1.0e8,0.0,0.0] 
bounds = hcat(lb,up)

```

---

_[View the full topic](https://discourse.julialang.org/t/nested-if-statements-better-formulation/49715)._
