Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Math problems  RSS feed

 
Katrina Cobb
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm trying to write a program to calculate for any positive value of x. I have to use the expression: square root of(7x^4 + 5x^3 + 3x^2 + x). I have it up till the part where I have to incorporate the sqrt() and pow() methods in order to get the answer. Any advice? Thanks...
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to JavaRanch!

What have you tried so far? You might start small to make sure you're using the methods correctly -- for example, just print out the square root of 9, or try raising 5 to the 2nd power.
 
Katrina Cobb
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I feel like an idiot for not thinking of that
...thanks!
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You do not need, and should not use, pow() for this expression. All the powers are integers, so you can just use ordinary multiplication, which is much faster than pow() and more accurate, too.

Also, you have a polynomial there, so you can refactor, to make the number of operations smaller.

For instance: -

x^4 + 2 x^3 + 3 x^2 + x + 4

is refactorable to

4 + x ( 1 + x ( 3 + x ( 2 + x ) ) )

Or something like that. The general point is that, when you have to implement a mathematical formula in a computer program, you should first take a good look at the formula itself, to see if it can be simplified and to see how it is best implemented on a computer.
[ September 25, 2006: Message edited by: Peter Chase ]
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!