Roots of a function: Difference between revisions

Content added Content deleted
m (→‎{{header|FreeBASIC}}: fixed indent+removed emply lines+added output template)
Line 1,214: Line 1,214:
=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
Simple bisection method.
Simple bisection method.
<lang freebasic>
<lang freebasic>#Include "crt.bi"

#include "crt.bi"
const iterations=20000000
const iterations=20000000


Line 1,222: Line 1,220:
dim as double last,st=(max-min)/iterations,v
dim as double last,st=(max-min)/iterations,v
for n as double=min to max step st
for n as double=min to max step st
v=f1(n)
v=f1(n)
if sgn(v)<>sgn(last) then
if sgn(v)<>sgn(last) then
redim preserve a(1 to ubound(a)+1)
redim preserve a(1 to ubound(a)+1)
a(ubound(a))=n
a(ubound(a))=n
O=n+st:exit sub
O=n+st:exit sub
end if
end if
last=v
last=v
next
next
end sub
end sub


function roots(f1 as function(as double) as double,min as double,max as double, a() as double) as long
function roots(f1 as function(as double) as double,min as double,max as double, a() as double) as long
Line 1,236: Line 1,234:
dim as double last,O,st=(max-min)/iterations,v
dim as double last,O,st=(max-min)/iterations,v
for n as double=min to max step st
for n as double=min to max step st
v=f1(n)
v=f1(n)
if sgn(v)<>sgn(last) and n>min then bisect(f1,n-st,n,O,a()):n=O
if sgn(v)<>sgn(last) and n>min then bisect(f1,n-st,n,O,a()):n=O
last=v
last=v
Line 1,260: Line 1,258:
print "in range -20 to 20"
print "in range -20 to 20"
print "All roots approximate"
print "All roots approximate"
print "number","root to 6 dec places","function value at root"
print "number","root to 6 dec places","function value at root"
for n as long=1 to ubound(r)
for n as long=1 to ubound(r)
print n,CRound(r(n),6),,defn(r(n))
print n,CRound(r(n),6),,defn(r(n))
next n
next n
end if
end if
sleep
sleep</lang>
{{out}}
</lang>
<pre>
<pre>in range -20 to 20
in range -20 to 20
All roots approximate
All roots approximate
number root to 6 dec places function value at root
number root to 6 dec places function value at root
1 0 -2.929925652002424e-009
1 0 -2.929925652002424e-009
2 1 1.477781779325033e-009
2 1 1.477781779325033e-009
3 2 -2.897852187377925e-009
3 2 -2.897852187377925e-009</pre>

</pre>


=={{header|Go}}==
=={{header|Go}}==