0

I have a known function:

eq = function(x){(4E-11*x^4)-(2E-8*x^3)-(1E-5*x^2)+(0.0132*x)+0.1801}

I want to get x values from known y values. However, because of floating point arithmetics, I cannot use which as in this question: How to find the x-value given the y-value from a plot in R.

Is there a way to get the exact x values knowing y, or do I have to go the approx way such as suggested in this example predict x values from simple fitting and annoting it in the plot ?

EvenStar69
  • 243
  • 3
  • 15

2 Answers2

2

Perhaps you could use uniroot. Here's a rough solution:

# Original function
eq <- function(x){(4E-11*x^4)-(2E-8*x^3)-(1E-5*x^2)+(0.0132*x)+0.1801}

# Find x value corresponding to y value
find_y <- function(y, lb = 0, ub = 1e6, acc = 1e-3){
  uniroot(function(x)eq(x)-y, c(lb, ub), tol = acc)
}

This finds the where eq(x)-y is zero. You need to specify the interval to look in (defined by lb & ub) and also an accuracy (acc), although I've added default values for simplicity.

# Test the y finding function
find_y(0.3)

# $`root`
# [1] 9.147868
# 
# $f.root
# [1] -1.330955e-09
# 
# $iter
# [1] 26
# 
# $init.it
# [1] NA
# 
# $estim.prec
# [1] 5e-04

In this output, root is the x value corresponding to y=0.3. Let's check the result in your original equation:

# > eq(9.147868)
# [1] 0.3

An implicit assumption is that there is only one y value corresponding to your x value in the given interval.

Dan
  • 11,370
  • 4
  • 43
  • 68
  • Indeed, I know in the interval I'm working there is only on x per y. Your solution match my needs, thank you ! – EvenStar69 Jan 11 '19 at 14:59
1

A quartic equation can have 0,2, or 4 solutions. If it was me, I would graph the function over a large interval and inspect to get an idea where, if anywhere, there are roots. Then why not simply use gradient descent ? There is a formula that will give an 'exact' solution for any quartic equation- you can find that with the help of google, but... It is highly unlikely that a computer can give an exact solution for many reasons. Two are the floating point issue you meant, but another big issue is that one can't write an 'exact' number for most solutions because an irrational number can only be written in decimal form as an infinite decimal with no repeating pattern.

meh
  • 218
  • 1
  • 9